Creating Arrays

PHP provides the array( ) language construct that creates arrays. The following examples show how arrays of integers and strings can be constructed and assigned to variables for later use:
$numbers = array(5, 4, 3, 2, 1);

$words = array("Web", "Database", "Applications");



// Print the third element from the array of integers: 3

print $numbers[2];



// Print the first element from the array of strings: "Web"

print $words[0];

By creating arrays this way, PHP assigns integer keys, or indexes to each element. By default, the index for the first element in an array is 0—this may seem odd but think of the index as an offset from the starting position in an array. The values contained in an array can be retrieved and modified using the bracket [ ] syntax. You can also create an array by assigning elements to a new, unset variable. The following code fragment illustrates the bracket syntax with an array of strings:
$newArray[0] = "Potatoes";

$newArray[1] = "Carrots";

$newArray[2] = "Spinach";



// Replace the third element

$newArray[2] = "Tomatoes";

In this example, PHP automatically treats $newArray as an array without a call to array( ).
An empty array can be created by assigning to a variable the return value of array( ). Values can then be added using the bracket syntax. PHP automatically assigns the next numeric index as the key (the largest integer key value plus one) when a key isn't supplied. The result of the following fragment is an array containing three items.
$shopping = array( );



$shopping[] = "Milk";

$shopping[] = "Coffee";

$shopping[] = "Sugar";

It's also easy to print individual element values themselves:
print $shopping[0];   // prints "Milk"

print $shopping[1];   // prints "Coffee"

print $shopping[2];   // prints "Sugar"