PHP Indexed Arrays
PHP Indexed Arrays
In indexed arrays each item has an index number.
The first array item has index 0, the second array item has index 1, etc.
Example
Create and display an indexed array:
$cars = array("Volvo", "BMW", "Toyota");
var_dump($cars);
Try it Yourself »
Access Array Item
To access a specific array item, refer to the index number.
Example
Output the first array item:
$cars = array("Volvo", "BMW", "Toyota");
echo $cars[0];
Try it Yourself »
Change Value of Array Item
To change the value of an array item, use the index number:
Example
Change the value of the second item:
$cars = array("Volvo", "BMW", "Toyota");
$cars[1] = "Ford";
var_dump($cars);
Try it Yourself »
Loop Through an Indexed Array
To loop through and print all the values of an indexed array, use a
foreach loop, like this:
Example
Display all array items:
$cars = array("Volvo", "BMW", "Toyota");
foreach ($cars as $x) {
echo "$x <br>";
}
Try it Yourself »
For a complete reference of all array functions, go to our complete PHP Array Reference.