An array is an ordered set of variables where each variable is known as an element. Arrays in PHP can hold integers, floats, Booleans, strings, objects, other arrays as well as values of mixed type.
Arrays in PHP can be numbered or associative.
In a numbered array the elements are accessed by a numeric index.
In an associative array the elements are accessed by a text string. This is useful when working with databases.
Creating an Array
The array() construct is used to create an array.
A Numbered Array
The index for the first element in an array is 0 by default but it can start at any numeric value you choose.
Example of a Numbered array
<?php
$names = array ("Tom", "Dick", "Harry");
// Print out the second element in the array
echo ($names[1]);
?>
To start the array index at a numeric value other than the default 0 or if you wish to leave gaps in the array it can be done as below.
Example of a Numbered array with Gaps
<?php
/* This starts the array at element 1 and
leaves out evenly numbered elements */
An empty array can be created and values added later in the script using the bracket syntax. If an index isn't supplied inside the bracket then PHP automatically assigns the highest current index + 1.
If an index is supplied inside the bracket then it will overwrite the current value, if it exists, with the new value.
Creating an Empty array then Updating it
<?php
$names = array ();
/* Later on in the script
the values can be added */
The foreach statement is specially designed for use with arrays - both numbered and associative. The loop executes once for each element in the array and takes two forms.
The first form assigns the value in each element to a variable identified with the as keyword.
The second form assigns both the key and the value in each element to a pair of variables identified with the as keyword.