Indexed Arrays
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.
The shortcut
To find an item, count from zero: the nth item lives at index n minus 1. To find the last one, use count minus 1.
The list
$featured = ["Dune", "Persuasion", "Ulysses", "Beloved"];
The classic slip is reaching for $featured[count($featured)]. That index is always one past the end.
Drills
Answer fast — trust the rule.
With $featured = ["Dune", "Emma", "Ulysses"];, what is $featured[1]?
How do you add "Beloved" to the end of $featured?
An array has 7 items. What is the index of the last one?
After unset($featured[1]) on a three-item array, which indexes remain?
Remember
- An indexed array numbers items from 0; the last is count minus 1.
- Shortcut: position n lives at index n − 1; append with
$arr[] = .... - Trap: unset leaves a gap in the numbering until you call array_values.
