PHP / CHAPTER 04
Arrays as ordered maps
IntermediateHandle keys, filtering, and iteration intentionally.
By the end of this chapter
- Distinguish list-shaped arrays from keyed arrays
- Preserve or reindex keys deliberately
- Avoid lingering foreach references
The idea
A PHP array is an ordered map rather than only a contiguous indexed sequence. It can represent a list, a keyed record, or a lookup table. Know which shape your function promises. Filtering preserves existing keys, so a filtered list can have gaps; array_values rebuilds sequential integer keys when a list-shaped result is required, including before JSON serialization.
Foreach visits entries in their array order and can expose both key and value. Iterating by reference allows direct changes, but the loop variable remains a reference to the final element unless you unset it afterward. Prefer ordinary iteration when constructing a new result. Be deliberate about key conversion, because certain numeric string keys become integer keys and can collide with an existing integer key.
<?php
$values = [3, 8, 5];
$kept = array_filter($values, fn(int $n): bool => $n >= 5);
echo json_encode(array_values($kept)), "
";[8,5]
Filtering retains keys 1 and 2. array_values reindexes the result, producing a JSON list with consecutive positions.
Try it yourself
Return a sequential array containing only positive amounts while preserving their original order.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING