PHP Indexed Arrays
Every item in an indexed array is identified by a number, its index.
Counting starts at 0: the first item is at index 0, the next at index 1, and the numbers keep going up from there.
Example
Build an indexed array and print its contents with var_dump():
Prompt
Write a PHP script that creates an indexed array with "Volvo", "BMW", and "Toyota" using the array() function, then displays it with var_dump().
Output: PHP script
index.php
<?php
$cars = array("Volvo", "BMW", "Toyota");
var_dump($cars);
?>
Access Array Item
Use the index number inside brackets to read one particular item.
Example
Print the item at index 0, the first car:
Prompt
Write a PHP script that creates an indexed array with "Volvo", "BMW", and "Toyota", then prints the first item using its index number.
Output: PHP script
index.php
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo $cars[0];
?>
Change Value of Array Item
To give an item a new value, assign to its index number:
Example
Replace the second item, at index 1:
Prompt
Write a PHP script that creates an indexed array with "Volvo", "BMW", and "Toyota", changes the second item to "Ford", then displays the array with var_dump().
Output: PHP script
index.php
<?php
$cars = array("Volvo", "BMW", "Toyota");
$cars[1] = "Ford";
var_dump($cars);
?>
Loop Through an Indexed Array
A foreach loop goes through the array one item at a time, which makes it easy to print everything:
All the array functions are described in our PHP Array Reference.
Example
Print each car on its own line:
Prompt
Write a PHP script that creates an indexed array with "Volvo", "BMW", and "Toyota", then uses a foreach loop to print each item followed by an HTML line break.
Output: PHP script
index.php
<?php
$cars = array("Volvo", "BMW", "Toyota");
foreach ($cars as $x) {
echo "$x <br>";
}
?>