PHP Tutorial – 06 – Arrays
An array is used to store a collection of values under a single variable name. PHP has three different kinds of arrays: numeric, associative, and multi-dimensional.
Numeric arrays
Numeric arrays store each element in the array with a numeric index. The elements can be assigned values all at once with the array constructor.
$a = array(1,2,3);
The elements can also be assigned one at a time by referencing each element with its index in square brackets.
$a[0] = 1; $a[1] = 2; $a[2] = 3;
The index can also be left out to add the value to the end of the array.
$a[] = 4; // $a[3]
Note that the capacity of the array is handled automatically and that the index of the array elements begins with zero.
To use the value of an element in the array specify the index of that element inside the square brackets.
echo "Numbers: $a[0] $a[1] $a[2] $a[3]";
Associative arrays
In associative arrays the key is given a name instead of an index. The double arrow operator (=>) is used to tell which key refer to what value.
$b = array("one" => "a", "two" => "b", "three" => "c"); $b["one"] = "a"; $b["two"] = "b"; $b["three"] = "c"; echo "Letters: " . $b["one"] . $b["two"] . $b["three"];
This operator can also be used with the numerical array’s constructor to decide in which element a value will be placed.
Multi-dimensional numeric arrays
The multi-dimensional array is an array that contains other arrays. A two dimensional array can be constructed like this:
$a = array(array("00","01"),array("10","11"));
The elements can just as well be assigned separately, using two sets of square brackets.
$a[0][0] = "00"; $a[0][1] = "01"; $a[1][0] = "10"; $a[1][1] = "11";
They are also referenced in this same way.
echo $a[0][0] . $a[0][1] . $a[1][0] . $a[1][1];
Multi-dimensional associative arrays
As with single dimensional arrays the key can be given a name to make it into a multi-dimensional associative array, also called a hash table.
$b = array("one"=>array("00","01")); echo $b["one"][0] . $b["one"][1];
Multi-dimensional arrays can have more than two dimensions by adding additional sets of square brackets.
$c[0][0][0][0] = "0000"; // four dimensional
Combined numeric and associative arrays
Associative and numerical arrays can actually be combined in the same array. Just be sure to access them in the same way as they’ve been set.
$b = array("one"=>array("a0","a1"), 1=>array("10","11")); echo $b["one"][0] . $b["one"][1] . $b[1][0] . $b[1][1];
If you like this tutorial please +1 it:


![[Affiliate link] Total Training]( http://d3qzmfcxsyv953.cloudfront.net/images/pvt-affiliates/totaltraining.png)
![[Affiliate link] Lynda](http://d3qzmfcxsyv953.cloudfront.net/images/pvt-affiliates/lynda.png)

