01 · THE IDEAREAD → TRY → LEARN
What an array is
A PHP array is an ordered map: it links keys to values. For a simple list you do not have to choose the keys. PHP numbers the items for you, starting at 0.
You can create an array with the short syntax []. Read an item by putting its key in square brackets after the variable.
$colors = ["red", "green", "blue"];
echo $colors[0], " ", $colors[2], " ", count($colors);red blue 3
The first item has key 0, so the last of three items has key 2. The function count() returns how many items the array holds. Asking for a key that does not exist produces a warning and gives null, so check the position you request.
Appending with empty brackets
To add to the end of an array, assign to $array[]. When you leave the key out, PHP uses the largest integer key used so far plus one. Existing entries stay where they are.
If you assign an explicit key, later appends continue from the highest integer key:
$numbers = [10, 20];
$numbers[] = 30;
$numbers[7] = 70;
$numbers[] = 80;
echo implode(",", array_keys($numbers)), "|", implode(",", $numbers);0,1,2,7,8|10,20,30,70,80
The keys are 0, 1, 2, 7, 8. Appending never overwrites an earlier item, but it can leave gaps if you have set keys by hand.
Arrays passed to functions
When you pass an array to a function, the function receives its own copy by default. If you append inside the function and return the array, the caller's original variable is unchanged unless it assigns the result back. This makes small helper functions easy to reason about: they take a list and return a new list.
Common mistakes
- Writing
$items[0] = $itemreplaces the first entry instead of adding one. - Returning
[$item]creates a brand-new array and throws away everything that was passed in. - Using
array_unshift()adds the value to the front, not the end.
Practice
Write append_item so it returns the original list with the new item placed last.
Variables · Strings
- Create an indexed array
- Append a value without losing existing entries