Child

PHP Arrays


What is an Array?

Arrays can be used in many ways to store and organize data quickly and efficiently. It is one of the more useful data types available to any programming language. Arrays can most easily be described as an ordered list of elements. You can access the individual elements by referring to their index position within the array. The position is either specified numerically or by name. An array with a numeric index is commonly called an indexed array while one that has named positions is called an associative array. In PHP, all arrays are associative, but you can still use a numeric index to access them.

An array stores multiple values in one single variable:

Example

<?php
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>

Create an Array in PHP

In PHP, the array() function is used to create an array:

array();

In PHP, there are three types of arrays:

  • Indexed arrays - Arrays with numeric index
  • Associative arrays - Arrays with named keys
  • Multidimensional arrays - Arrays containing one or more arrays

PHP Indexed Arrays

There are two ways to create indexed arrays:

The index can be assigned automatically (index always starts at 0):

$cars=array("Volvo","BMW","Toyota");

or the index can be assigned manually:

$cars[0]="Volvo";
$cars[1]="BMW";
$cars[2]="Toyota";

The following example creates an indexed array named $cars, assigns three elements to it, and then prints a text containing the array values:

Example

<?php
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>

Get The Length of an Array - The count() Function

The count() function is used to return the length (the number of elements) of an array:

Example

<?php
$cars=array("Volvo","BMW","Toyota");
echo count($cars);
?>

Loop Through an Indexed Array

To loop through and print all the values of an indexed array, you could use a for loop, like this:

Example

<?php
$cars=array("Volvo","BMW","Toyota");
$arrlength=count($cars);

for($x=0;$x<$arrlength;$x++)
  {
  echo $cars[$x];
  echo "<br>";
  }
?>

PHP Associative Arrays

Associative arrays are arrays that use named keys that you assign to them.

There are two ways to create an associative array: 

$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");

or:

$age['Peter']="35";
$age['Ben']="37";
$age['Joe']="43";

The named keys can then be used in a script:

Example

<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>