Indexed Arrays
A PHP indexed array uses integer keys in an ordered map. Keys can have gaps or start elsewhere, so the final key is not necessarily count minus one.
Follow numeric keys, insertion and traversal without assuming every array is a dense list.
Pageturn's front page lists this week's featured books. You could make $book1, $book2, $book3, but then adding a fourth means renaming and rewriting. An array keeps the whole list under one name, in order, and grows when you need it to.
The rule
An indexed array numbers its items from 0, so the last one is count minus 1.
<?php
$featured = ["Dune", "Emma", "Ulysses"];
echo $featured[0]; // Dune
echo $featured[2]; // Ulysses
echo count($featured); // 3
$featured[] = "Beloved"; // add to the end: now index 3
$featured[1] = "Persuasion"; // replace EmmaWhat each piece does:
- Square brackets
[...]create the array. The olderarray("Dune", "Emma")form still works, but the short form is standard now. $featured[0]reads the first item. Indexes are integers counting up from 0.count()gives the number of items, so the last index iscount($featured) - 1.$featured[] = ...with empty brackets appends a new item at the next index.- Reading a missing index such as
$featured[10]givesnullwith an "Undefined array key" warning.
Useful helpers: in_array("Dune", $featured) tests membership, sort($featured) puts items in order (changing the array itself), and implode(", ", $featured) joins them into one string for display.
One surprise: unset($featured[1]) removes the item but does not renumber the rest. The array then has indexes 0, 2 and 3, and $featured[1] no longer exists. Call array_values($featured) to get a fresh 0, 1, 2 numbering.