An indexed array is an array where each item has a numeric index. By default, the index starts at 0 and increases by one for each subsequent item.
To access an element, you use square brackets with the index number of the item you want.
<?php
$cars = ["Volvo", "BMW", "Toyota"];
echo $cars[0]; // Outputs: Volvo
echo $cars[1]; // Outputs: BMW
?>
You can change the value of an existing element by assigning a new value to its specific index.
<?php
$cars = ["Volvo", "BMW", "Toyota"];
$cars[1] = "Ford"; // Overwrites BMW with Ford
echo $cars[1]; // Outputs: Ford
?>
To print all the values of an indexed array, you can use a for loop (using the length of the array) or a foreach loop.
<?php
$cars = ["Volvo", "BMW", "Toyota"];
foreach ($cars as $car) {
echo "$car <br>";
}
?>
You can add a new item to the end of an indexed array using empty square brackets []. PHP will automatically assign the next available numeric index.
<?php
$cars = ["Volvo", "BMW"];
$cars[] = "Toyota"; // Adds to index 2
print_r($cars);
?>
$cars[10] when there are only 3 items), PHP will return a "Warning: Undefined array key" error.
print_r() or var_dump() functions to quickly see the structure and contents of an array during development.