PHP Indexed Arrays
Indexed arrays store values in numbered slots, making them the natural choice for ordered lists.
How indexed arrays work
An indexed array assigns an integer key to each value automatically, beginning at 0 for the first item, 1 for the second, and so on. Because the keys follow a predictable sequence, indexed arrays are perfect whenever the order of the values matters, such as a queue of jobs, a list of file names, or the days of the week.
Creating and reading an indexed array
<?php
$languages = ["PHP", "Python", "Go"];
echo $languages[0]; // PHP
echo $languages[1]; // Python
echo $languages[2]; // Go
// count() returns the number of items
echo count($languages); // 3
?>Adding items to the list
You can grow an indexed array by assigning to an empty bracket pair. PHP keeps track of the highest integer key used so far and gives the new value the next number. You can also assign to a specific index, but be aware that skipping numbers leaves gaps rather than errors.
Appending values
<?php
$stack = [];
$stack[] = "first"; // key 0
$stack[] = "second"; // key 1
$stack[10] = "jump"; // key 10 (gap from 2 to 9)
$stack[] = "after"; // key 11, one past the highest key
print_r($stack);
?>Looping over an indexed array
The cleanest way to visit every element is a foreach loop, which hands you each value in order without you tracking an index. When you genuinely need the position, a classic for loop driven by count() gives you the numeric key as well.
Two ways to iterate
<?php
$colors = ["red", "green", "blue"];
// foreach: simplest for values
foreach ($colors as $color) {
echo $color . "\n";
}
// for: when you need the index
for ($i = 0; $i < count($colors); $i++) {
echo $i . ": " . $colors[$i] . "\n";
}
?>Common tasks on indexed arrays
- Add to the end with array_push() or the shorter $arr[] syntax.
- Remove the last element with array_pop(), which also returns it.
- Remove the first element with array_shift() and add to the front with array_unshift().
- Check whether a value exists with in_array() and find its index with array_search().
Reindexing after removal
<?php
$items = ["a", "b", "c", "d"];
unset($items[1]); // removes "b", leaves keys 0, 2, 3
$items = array_values($items);
print_r($items);
// keys are now 0, 1, 2 again
?>