Arrays, Keys & Ordered Maps

Arrays, Keys & Ordered Maps in PHP: --- Behind the ticket hall at a large railway terminus there is a long room with a counter across the front and wooden…


The Analogy: The Left-Luggage Office At The Terminus

Behind the ticket hall at a large railway terminus there is a long room with a counter across the front and wooden shelving from floor to ceiling behind it. A passenger hands over a holdall; the clerk tears the next stub off a numbered pad, loops one half through the handle with string, hands the other half across the counter, and sets the bag down on the first clear space. Nothing about the shelf is clever. The bags sit in the order they arrived, because that is the order in which the clerk walked down the row putting them there.

Not everything on the rack carries a number. Forty season-ticket holders keep a bag in the office permanently, and each of those has a small painted card instead of a stub: MORTON, ASHWORTH, PENGELLY. Those cards sit on the same shelving, interleaved with the numbered stubs, because there is only one rack in the room. To find anything at all the procedure is identical: read the labels until you find the one on the passenger's half of the ticket. The label identifies the parcel. The position on the shelf is only where it happens to be standing.

The numbered pad is the part that surprises people. It counts forward and never counts back. If stub 41 is torn off for a holdall and the holdall is collected an hour later, the pad does not reissue 41 -- it hands out 42, and the space where the holdall stood is an empty gap in an otherwise full row. A busy Saturday can end with a rack half empty and a pad that has reached 300. And when a passenger asks for a particular space by hand -- the photographer who insists on space 7 for the tripod he collects every Thursday -- the pad quietly advances past it, so the next stub torn off is 8 and not 2.

The failure mode arrives with the relief clerk on a Monday morning. Handed a ticket reading 40, he does not read the labels; he counts along the shelf, forty parcels from the left, and hands over a canvas grip belonging to somebody else. It worked all through the quiet week, because the rack had been filled from empty in one unbroken run and position and label happened to agree. The moment one parcel was collected out of order, or one named card was slotted in between two numbers, the two stopped agreeing -- and the relief clerk had no way of noticing, because the count still produced a parcel and the parcel still had a handle. That is the entire difficulty of the PHP array in one image: a labelled rack that usually looks like a numbered row, where code trusting the row instead of the labels is correct right up until the first gap.


Syntax or Core Structure

There is exactly one array type in PHP: no separate list, dictionary or tuple. What the manual calls an array is an ordered map -- a sequence of key-and-value pairs that remembers its insertion order, where every key is either an int or a string. Anything that looks like a list, [10, 20, 30], is that same ordered map with the keys 0, 1, 2 filled in for you. The program below builds the rack a piece at a time, so you can watch the numbered pad advance.

<?php
declare(strict_types=1);

$rack = [];                          // an empty rack, no shelves used
$rack[] = "brown holdall";           // the pad hands out 0
$rack[] = "wicker basket";           // then 1
$rack[7] = "steamer trunk";          // the photographer insists on space 7
$rack[] = "hat box";                 // the pad has advanced past 7, so this is 8
$rack["season:MORTON"] = "golf bag"; // a painted card, not a stub
$rack["12"] = "fishing rods";        // the string "12" is stored as the int 12
$rack[] = "cello case";              // therefore this is 13, not 9

foreach ($rack as $ticket => $item) {
    printf("%-16s %s%s", var_export($ticket, true), $item, PHP_EOL);
}
echo "count: ", count($rack), PHP_EOL;

unset($rack[7]);                     // the tripod is collected; the gap stays
echo "after unset(7): ", implode(", ", array_keys($rack)), PHP_EOL;

$rack[] = "kit bag";                 // the pad still counts forward
echo "kit bag took key: ", array_key_last($rack), PHP_EOL;
echo "is a list: ", var_export(array_is_list($rack), true), PHP_EOL;

$renumbered = array_values($rack);   // re-label from zero, order preserved
echo "renumbered   : ", implode(", ", array_keys($renumbered)), PHP_EOL;
echo "is a list: ", var_export(array_is_list($renumbered), true), PHP_EOL;

Output:

0                brown holdall
1                wicker basket
7                steamer trunk
8                hat box
'season:MORTON'  golf bag
12               fishing rods
13               cello case
count: 7
after unset(7): 0, 1, 8, season:MORTON, 12, 13
kit bag took key: 14
is a list: false
renumbered   : 0, 1, 2, 3, 4, 5, 6
is a list: true

Read the key column carefully: var_export() reports the type of each key, not just its text. The first four print bare, so they are integers; the fifth prints inside single quotes, so it is a string; the sixth prints bare even though it was written as "12", because PHP converted it on the way in and there is no way back. Three behaviours are worth memorising. The hat box landed on 8 rather than 2, and the kit bag on 14 rather than 2 or 7, because the next-integer counter is one above the largest integer key ever used and not the first hole in the sequence. The unset() left a gap and compacted nothing, so count($rack) and array_key_last($rack) are now unrelated quantities. And array_is_list() said false for a perfectly healthy array, because it asks one narrow question -- are the keys exactly the integers 0 to n-1, in that order -- and any gap, string key or reordering answers no.


Technical Depth: What Really Happens Behind The Counter

One Structure, Two Access Paths

Internally the array is one block of memory holding the pairs in insertion order, plus a hash table mapping each key to a position in that block. That is why foreach is a straight scan and $rack["season:MORTON"] is still a single lookup, and why unset() leaves a gap instead of shuffling everything to its right -- shuffling would invalidate every other position at once. When the keys really are 0 to n-1, PHP drops the hash table and uses the block directly. That is the packed representation, and it is why array_is_list() is cheap and why array_values() after a filter is worth the call.

Key Coercion, Exactly

A key may only ever be an int or a string; anything else in the brackets is converted first. The rule for strings is narrower than most people assume: a string key becomes an integer if and only if it is the canonical decimal spelling of an integer that fits in a platform int -- no leading zeros, no leading plus, no surrounding whitespace, no decimal point, no exponent, one spelling of zero.

Written asKey storedKey typeWhy
$a[7]7intan integer is used as it is
$a["7"]7intcanonical, so it is converted
$a["07"]07stringa leading zero is not canonical
$a["+7"]+7stringa leading plus is not canonical
$a[" 7"]space then 7stringsurrounding whitespace is not canonical
$a["7.0"]7.0stringnumeric, but not an integer spelling
$a["1e2"]1e2stringexponent form is not an integer spelling
$a["-7"]-7inta leading minus is canonical
$a["-0"]-0stringzero has exactly one canonical spelling
$a[7.9]7intfloats truncate toward zero
$a[true]1intbool to int
$a[false]0intbool to int
$a[null]empty stringstringthe empty-string key is legal
$a["9223372036854775808"]the digitsstringoutside the 64-bit int range

Two of those rows carry teeth. $a[7.9] silently truncates, and since PHP 8.1 it raises a deprecation notice when the truncation loses information -- the language admitting the conversion was a mistake. And $a[null] is not an error: it stores under the empty-string key, so a null identifier you forgot to validate quietly overwrites the same slot every time round the loop. You never have to guess which way a key went, because array_keys() and var_export() will tell you.

<?php
declare(strict_types=1);

$a = [];
$a[7]     = 'a';
$a["7"]   = 'b';   // the same slot as above
$a["07"]  = 'c';
$a["-7"]  = 'd';
$a["-0"]  = 'e';
$a[true]  = 'f';
$a[null]  = 'g';
$a["1e2"] = 'h';

echo var_export(array_keys($a), true), PHP_EOL;
echo "count: ", count($a), PHP_EOL;
echo "slot 7 holds: ", $a[7], PHP_EOL;

Output:

array (
  0 => 7,
  1 => '07',
  2 => -7,
  3 => '-0',
  4 => 1,
  5 => '',
  6 => '1e2',
)
count: 7
slot 7 holds: b

Eight assignments produced seven slots, because $a["7"] was the same slot as $a[7] and overwrote it. The empty-string key prints as '' at index 5, which is the clearest possible warning that $a[$maybeNull] is not the harmless expression it looks like.

Copy Semantics: Arrays Are Values, Objects Inside Them Are Not

An array is a value: assigning one copies it, passing one to a function copies it, returning one copies it. PHP makes that affordable with copy-on-write -- the two variables share one buffer until somebody writes -- but the observable behaviour is a plain copy and you should reason about it that way. What is not copied is any object inside the array. An object is held by handle, and duplicating the array duplicates the handle, not the thing it points at.

<?php
declare(strict_types=1);

$monday = [41, 42, 43];
$tuesday = $monday;      // a copy, not an alias
$tuesday[] = 44;
printf("monday %d, tuesday %d%s", count($monday), count($tuesday), PHP_EOL);

$labels = [new stdClass()];
$labels[0]->owner = "Morton";
$duplicate = $labels;    // the array is copied, the object is not
$duplicate[0]->owner = "Ashworth";
echo "original array now reads: ", $labels[0]->owner, PHP_EOL;

$alias = &$monday;       // this really is an alias
$alias[] = 99;
printf("monday %d after writing through the reference%s", count($monday), PHP_EOL);

Output:

monday 3, tuesday 4
original array now reads: Ashworth
monday 4 after writing through the reference

The middle line catches people out in any codebase that has started putting entities into arrays. The array was copied faithfully; the object was never copied, so writing through $duplicate wrote into the object $labels can see. A genuinely independent copy of an array of objects means cloning the objects yourself.

The Sorting Family

There are nine core sort functions, differing along three axes: what they order by, whether they keep the keys, and where the comparison comes from. Every one takes the array by reference, mutates it in place, and returns bool -- not the sorted array.

FunctionOrders byKeys afterwardsComparison
sortvaluerenumbered from 0built in, ascending
rsortvaluerenumbered from 0built in, descending
usortvaluerenumbered from 0your callback
asortvaluepreservedbuilt in, ascending
arsortvaluepreservedbuilt in, descending
uasortvaluepreservedyour callback
ksortkeypreservedbuilt in, ascending
krsortkeypreservedbuilt in, descending
uksortkeypreservedyour callback

Since PHP 8.0 all of them are stable, which is a genuinely useful guarantee: equal elements keep their relative order, so sorting by a secondary field first and a primary field second gives a correct multi-key ordering out of two simple passes. Before 8.0 the order of tied elements was unspecified and did vary with array size. The built-in comparison is the same loose comparison < uses, fine for an array of one type and a trap for mixed types: pass a sort flag such as SORT_STRING or SORT_NUMERIC, or use a u variant with a typed callback returning int.

Searching, Membership And Set Operations

<?php
declare(strict_types=1);

$row = ['ticket' => 12, 'owner' => null];
var_dump(isset($row['owner']));                 // the key exists, the value is null
var_dump(array_key_exists('owner', $row));
var_dump(in_array("12", [12, 13]));             // loose by default
var_dump(in_array("12", [12, 13], true));       // strict
var_dump(in_array(0, ["brown", "wicker"]));     // false since PHP 8.0
var_dump(array_search(13, [12, 13, 14], true));
var_dump(array_search(99, [12, 13, 14], true));

// the set functions compare as strings and keep the keys they were handed
$monday  = [41, 42, 43];
$tuesday = [42, 43, 44];
echo "still here: ", implode(",", array_intersect($monday, $tuesday)), PHP_EOL;
echo "collected : ", implode(",", array_diff($monday, $tuesday)), PHP_EOL;
echo "new today : ", implode(",", array_diff($tuesday, $monday)), PHP_EOL;
echo "keys kept : ", implode(",", array_keys(array_diff($tuesday, $monday))), PHP_EOL;
echo "counted   : ", count(array_diff($tuesday, $monday)), PHP_EOL;

Output:

bool(false)
bool(true)
bool(true)
bool(false)
bool(false)
int(1)
bool(false)
still here: 42,43
collected : 41
new today : 44
keys kept : 2
counted   : 1

The first pair is the commonest array bug in PHP: isset() answers "does this key exist and hold something other than null", which is two questions at once. Where null is meaningful -- an uncollected parcel has no collection day -- isset() says the key is missing when it is present, and your default overwrites real data. The array_search() lines are the reason to always pass true as the third argument: both it and in_array() compare loosely by default, and array_search() returns false for "not found" while also being able to return the perfectly valid key 0, so its result must be tested with !== and never with a plain truth test.

One element came back from the last diff, and its key is 2, not 0. Hand that array to json_encode() and you get the object {"2":44} rather than the array [44], and a client expecting to call .map() on it breaks. array_values() is the fix, applied at the boundary where the data leaves PHP.

Destructuring, Auto-Vivification And The Two Ways To Join

<?php
declare(strict_types=1);

['owner' => $who, 'size' => $class] = ['owner' => 'Delaney', 'size' => 'large', 'day' => 2];
printf("%s left a %s item%s", $who, $class, PHP_EOL);

[$first, , $third] = ['holdall', 'basket', 'trunk'];   // the hole skips a slot
printf("first %s, third %s%s", $first, $third, PHP_EOL);

foreach ([[41, 'Morton'], [42, 'Ashworth']] as [$ticket, $owner]) {
    printf("ticket %d belongs to %s%s", $ticket, $owner, PHP_EOL);
}

$shelves = [];
$shelves['bay3']['top'][] = 'trunk';     // both levels are created for you
$shelves['bay3']['top'][] = 'hat box';
printf("bay3 top holds %d items%s", count($shelves['bay3']['top']), PHP_EOL);

$base    = ['small' => 350];
$extra   = ['medium' => 520, 'small' => 999];
$merged  = array_merge($base, $extra);
$plussed = $base + $extra;
echo "merge keys ", implode(",", array_keys($merged)), " and small is ", $merged['small'], PHP_EOL;
echo "plus  keys ", implode(",", array_keys($plussed)), " and small is ", $plussed['small'], PHP_EOL;
echo "merge on lists: ", implode(",", array_merge([1, 2], [3, 4])), PHP_EOL;
echo "plus  on lists: ", implode(",", [1, 2] + [3, 4]), PHP_EOL;

Output:

Delaney left a large item
first holdall, third trunk
ticket 41 belongs to Morton
ticket 42 belongs to Ashworth
bay3 top holds 2 items
merge keys small,medium and small is 999
plus  keys small,medium and small is 350
merge on lists: 1,2,3,4
plus  on lists: 1,2

The last four lines are the whole difference. For string keys, array_merge() lets the right-hand side win and + lets the left-hand side win, which makes + the natural way to apply defaults: $options + $defaults keeps whatever the caller supplied. For integer keys the divergence is worse -- array_merge() renumbers them and appends everything, while + treats an existing integer key as occupied and discards the incoming value. That is why + silently dropped 3 and 4. The spread operator is a third option: [...$base, ...$extra] always renumbers integer keys, and accepts string keys only from PHP 8.1, where the last occurrence wins.

Note also that $shelves['bay3']['top'][] = 'trunk' worked on an empty array. PHP creates every missing intermediate level on a write, which is convenient and is also why a typo in a nested write never raises anything -- it just builds a new branch nobody reads.


Real World Example: The Left-Luggage Day Book

The office produces a day book at closing time. Every parcel deposited that week appears once, with the nights it has been on the shelf, what it has cost so far, and whether it is still there. The clerk then wants three things the raw ledger does not give directly: a summary by size class, the owners holding more than one ticket, and the parcels sitting longest, because after fourteen nights an item goes to lost property. Each of those is an array-shaping problem wanting a different shape -- the report rows a list, the size summary a map keyed by size class, the owner index a map from a name to a list of tickets -- and all three come out of a single pass.

<?php
declare(strict_types=1);

const RATES     = ['small' => 350, 'medium' => 520, 'large' => 780];
const SURCHARGE = ['small' => 0, 'medium' => 0, 'large' => 250];
const TODAY     = 11;
const LOST_AT   = 14;
const FMT       = "%-3s %-10s %-7s %3s %4s %6s %-10s %9s";

function money(int $pence): string
{
    return number_format($pence / 100, 2);
}

/**
 * @param array{owner:string, size:string, day:int} $item
 * @return array{nights:int, charge:int}
 */
function bill(array $item, ?int $outDay): array
{
    $nights = max(1, ($outDay ?? TODAY) - $item['day']);
    $charge = $nights * RATES[$item['size']] + SURCHARGE[$item['size']];

    return ['nights' => $nights, 'charge' => $charge];
}

// the ledger, keyed by ticket, in the order the parcels arrived
$deposits = [
    41 => ['owner' => 'Morton',   'size' => 'medium', 'day' => 1],
    42 => ['owner' => 'Ashworth', 'size' => 'small',  'day' => 1],
    43 => ['owner' => 'Delaney',  'size' => 'large',  'day' => 2],
    44 => ['owner' => 'Morton',   'size' => 'small',  'day' => 3],
    45 => ['owner' => 'Pengelly', 'size' => 'large',  'day' => 5],
    46 => ['owner' => 'Ashworth', 'size' => 'medium', 'day' => 6],
    47 => ['owner' => 'Trewin',   'size' => 'small',  'day' => 6],
];

// the collection book, keyed by ticket, written up as people call in
$collected = [41 => 4, 42 => 3, 44 => 9, 43 => 6];

$rows    = [];   // a list, for the report body
$byOwner = [];   // owner name to list of tickets
$bySize  = [];   // size class to running totals
$totals  = ['nights' => 0, 'charge' => 0, 'counter' => 0, 'shelf' => 0];

foreach ($deposits as $ticket => $item) {
    $outDay = $collected[$ticket] ?? null;
    ['nights' => $nights, 'charge' => $charge] = bill($item, $outDay);
    $size = $item['size'];

    $rows[] = ['ticket' => $ticket, 'owner' => $item['owner'], 'size' => $size,
        'in' => $item['day'], 'out' => $outDay, 'nights' => $nights,
        'charge' => $charge, 'state' => $outDay === null ? 'on shelf' : 'collected'];

    $byOwner[$item['owner']][] = $ticket;   // the inner list is created on write
    $bySize[$size]['items']  = ($bySize[$size]['items']  ?? 0) + 1;
    $bySize[$size]['nights'] = ($bySize[$size]['nights'] ?? 0) + $nights;
    $bySize[$size]['charge'] = ($bySize[$size]['charge'] ?? 0) + $charge;

    $totals['nights'] += $nights;
    $totals['charge'] += $charge;
    $totals[$outDay === null ? 'shelf' : 'counter'] += $charge;
}

echo "LEFT-LUGGAGE DAY BOOK -- DAY ", TODAY, PHP_EOL;
echo str_repeat("=", 59), PHP_EOL;
printf(FMT . "%s", "TKT", "OWNER", "SIZE", "IN", "OUT", "NIGHTS", "STATE", "CHARGE", PHP_EOL);
echo str_repeat("-", 59), PHP_EOL;

foreach ($rows as $r) {
    printf(FMT . "%s", $r['ticket'], $r['owner'], $r['size'], $r['in'],
        $r['out'] ?? '-', $r['nights'], $r['state'], money($r['charge']), PHP_EOL);
}
echo str_repeat("-", 59), PHP_EOL;

// RATES fixes the band order, so the summary cannot come out in hash order
foreach (array_keys(RATES) as $size) {
    $s = $bySize[$size] ?? ['items' => 0, 'nights' => 0, 'charge' => 0];
    printf(FMT . "%s", "", "", $size, "", "", $s['nights'],
        $s['items'] . " items", money($s['charge']), PHP_EOL);
}
echo str_repeat("-", 59), PHP_EOL;
printf(FMT . "%s", "", "", "TOTAL", "", "", $totals['nights'],
    count($rows) . " items", money($totals['charge']), PHP_EOL);
echo str_repeat("=", 59), PHP_EOL;

printf("counter %s   shelf %s   book %s%s",
    money($totals['counter']), money($totals['shelf']), money($totals['charge']), PHP_EOL);
$balanced = $totals['counter'] + $totals['shelf'] === $totals['charge'];
echo "cross-check: ", $balanced ? "balances" : "OUT OF BALANCE", PHP_EOL;

echo PHP_EOL, "OWNERS WITH MORE THAN ONE TICKET", PHP_EOL;
ksort($byOwner);                        // sorts in place, returns bool
foreach ($byOwner as $owner => $tickets) {
    if (count($tickets) < 2) {
        continue;
    }
    printf("%-10s %s%s", $owner, implode(", ", $tickets), PHP_EOL);
}

echo PHP_EOL, "OLDEST ON THE SHELF", PHP_EOL;
$shelf = array_values(array_filter($rows, fn(array $r): bool => $r['state'] === 'on shelf'));
usort($shelf, fn(array $a, array $b): int
    => [$b['nights'], $a['ticket']] <=> [$a['nights'], $b['ticket']]);
foreach ($shelf as $r) {
    printf("%-3d %-10s %2d nights %8s%s", $r['ticket'], $r['owner'], $r['nights'],
        money($r['charge']), PHP_EOL);
}
$overdue = array_filter($shelf, fn(array $r): bool => $r['nights'] >= LOST_AT);
printf("%d of %d have reached the %d night lost property limit%s",
    count($overdue), count($shelf), LOST_AT, PHP_EOL);

Output:

LEFT-LUGGAGE DAY BOOK -- DAY 11
===========================================================
TKT OWNER      SIZE     IN  OUT NIGHTS STATE         CHARGE
-----------------------------------------------------------
41  Morton     medium    1    4      3 collected      15.60
42  Ashworth   small     1    3      2 collected       7.00
43  Delaney    large     2    6      4 collected      33.70
44  Morton     small     3    9      6 collected      21.00
45  Pengelly   large     5    -      6 on shelf       49.30
46  Ashworth   medium    6    -      5 on shelf       26.00
47  Trewin     small     6    -      5 on shelf       17.50
-----------------------------------------------------------
               small                13 3 items        45.50
               medium                8 2 items        41.60
               large                10 2 items        83.00
-----------------------------------------------------------
               TOTAL                31 7 items       170.10
===========================================================
counter 77.30   shelf 92.80   book 170.10
cross-check: balances

OWNERS WITH MORE THAN ONE TICKET
Ashworth   42, 46
Morton     41, 44

OLDEST ON THE SHELF
45  Pengelly    6 nights    49.30
46  Ashworth    5 nights    26.00
47  Trewin      5 nights    17.50
0 of 3 have reached the 14 night lost property limit

One pass over the ledger produced three differently shaped arrays, none of which needed declaring in advance. $rows[] grew as a list, so it stays packed and foreach walks it in ledger order. $byOwner[$item['owner']][] grew as a map of lists, the inner list created by the first write for each name. $bySize grew as a map of running totals, and the ?? 0 on each accumulator is doing real work: without it the first + 1 would be adding to an undefined key, which in PHP 8 is a warning that yields null, so the code would appear to work while shouting into the log on every first-of-a-kind row.

The report uses one format string for every band. That is why the money column lands in the same nine characters on the parcel rows, the size bands and the grand total, and why widening the owner column later means editing one constant rather than five printf calls. The band order is equally deliberate: $bySize is keyed by size class and would emerge in whatever order the classes first appeared, so the summary loop iterates array_keys(RATES) instead. One array supplies the ordering, the other the numbers, and the report is identical whichever day it is run on.

The shelf listing shows two habits worth copying. array_filter() preserves keys, so its result is wrapped in array_values() immediately: the next thing that happens to $shelf is a usort() that would renumber it anyway, but the wrapping means the variable is a list at every point where somebody might read it. And the comparison sorts two arrays against each other rather than chaining comparisons by hand: [$b['nights'], $a['ticket']] <=> [$a['nights'], $b['ticket']] compares nights descending and falls through to ticket ascending only on a tie. Sorts have been stable since PHP 8.0, so 46 and 47 would have kept their ledger order anyway; the explicit tiebreak makes the ordering a property of the code, not the version.

Now the limits, and they are larger than the report admits. The most serious is that the whole thing iterates $deposits, so $collected is only ever read through $collected[$ticket] ?? null. A collection written up against a ticket that is not in the deposit ledger -- a mis-keyed number, a parcel taken in by the night shift on a different pad -- is never looked at, never charged and never reported. Worse, the cross-check: balances line cannot detect it, or anything else, because $totals['counter'] and $totals['shelf'] are accumulated from the same $charge in the same iteration that adds it to $totals['charge']. The two parts equal the whole by construction, so the check prints balances for every possible input, including inputs where money has gone missing. A reconciliation that cannot fail is worse than none, because it is read as evidence; the genuine check is count($collected) === count(array_intersect_key($collected, $deposits)). Second, RATES[$item['size']] on an unknown size class is a warning that evaluates to null, and $nights * null is 0, so a parcel logged as xl is stored free and the totals still agree with themselves. Third, max(1, ...) was written to charge a minimum of one night but it also swallows impossible data: a collection day earlier than the deposit day is billed as one night instead of rejected. Finally, TODAY is a compile-time constant and money() divides into a float before formatting -- harmless here, wrong as a general money representation.


Common Mistakes

  1. Treating every array as a list. A for ($i = 0; $i < count($a); $i++) loop

reads positions, not labels, so it silently skips data the moment a key is missing. Anything that has been through unset(), array_filter() or a hand-built map has gaps or names in it. Use foreach, or assert array_is_list($a) first.

  1. Forgetting that array_filter() preserves keys. Filtering [41, 42, 43] down

to one element can give [2 => 43], and json_encode() turns that into the object {"2":43} rather than [43]. Every client expecting a JSON array breaks, and only for the inputs that filtered something out. Wrap filters in array_values().

  1. Leaving in_array() and array_search() loose. Without the third argument

true they compare loosely, so in_array("12abc", [12]) is a question about PHP's comparison rules rather than about your data. Also test array_search() with !== false, because a genuine hit at key 0 is falsy.

  1. Using isset() to ask whether a key exists. isset() answers two questions

at once and returns false when the key is present but the value is null. Wherever null means something -- not collected yet, no middle name, no discount -- isset() reports the field as absent and your ?? default overwrites a deliberate null. Use array_key_exists() when the distinction matters.

  1. Assuming a numeric string key stays a string. $a["12"] and $a[12] are one

slot, so ticket numbers read out of a CSV as strings collide with an integer-keyed lookup elsewhere and neither side reports anything. The coercion is not symmetric either: "12" converts but "012" does not, so two numbers a human reads as equal become two different slots.

  1. Reaching for array_merge() when you meant +, or the reverse. For string

keys the right-hand side wins under array_merge() and the left-hand side wins under +. For integer keys array_merge() renumbers and keeps everything while + discards any incoming value whose key is already taken. Applying defaults is $given + $defaults; concatenating two lists is array_merge($a, $b); the other two combinations are bugs.

  1. Assigning the result of a sort. $sorted = sort($rows); puts true in

$sorted and quietly reorders $rows behind the caller's back, because every core sort takes its array by reference and returns bool. Sort a named copy on purpose: $sorted = $rows; usort($sorted, ...);.

  1. Leaving a reference bound after foreach ($a as &$v). The reference outlives

the loop and still points at the last element. A second, ordinary foreach ($a as $v) over the same array then writes each value into that last slot in turn, so [1, 2, 3] becomes [1, 2, 2] with no warning anywhere. Always unset($v) on the line after a by-reference loop, or avoid the form entirely.

  1. Reading a key that is not there. Since PHP 8.0 this is a warning, not an

error, and the expression evaluates to null. Null in arithmetic is 0, in string context the empty string, and in count() a TypeError. So a typo in a key name usually produces a plausible zero rather than a crash, which is the most effective way to make a financial report wrong and confident at the same time.


Best Practices

  • Decide list or map for every array, and keep it that way. Name it

accordingly, and where it matters put assert(array_is_list($rows)); at the boundary. Most array bugs are a list treated as a map or the reverse.

  • Call array_values() at every serialisation boundary. Anything through

array_filter(), array_unique() or array_diff() carries the old keys, and json_encode() will faithfully turn those keys into an object.

  • Always pass true to in_array() and array_search(), and compare the

result of array_search() with !== false. Loose comparison in a membership test is never what you meant.

  • **Use ?? for a missing-or-null default and array_key_exists() when the

difference matters.** Write the accumulator idiom as $t[$k] = ($t[$k] ?? 0) + $n; so the first increment is not a warning.

  • Build one canonical index per lookup you need. If the code searches the same

list twice, replace the searches with an array_column($rows, null, 'ticket') map built once. Repeated array_search() over a growing array is the commonest accidental quadratic loop in PHP.

  • Never sort by side effect into a new variable. Copy the array, name the copy

for what it is sorted by, then sort the copy. Reserve the u variants for real multi-key orderings and give the callback typed parameters and an int return.

  • Let one array supply the order and another the values when a report has fixed

bands. Iterating array_keys(RATES) rather than the accumulator makes the output independent of the order the input arrived in.

  • Keep money, counts and identifiers as integers inside arrays and format only

at the point of printing. A 'charge' => 4930 that becomes "49.30" in the printf argument list can be summed, compared and asserted on; a string cannot.


Practice Exercises

  1. Prove the coercion table. Write a script that assigns to $a under each of

the fourteen key forms in the table above, one at a time, and prints var_export(array_keys($a), true) after each assignment. Confirm which forms collide, and add a row for $a[-7.9] and $a["9223372036854775807"]. Explain in a comment why the count is smaller than the number of assignments.

  1. Break the day book, then fix it. Add 48 => 5 to $collected with no

matching deposit, and change ticket 47 to size 'xl'. Run the report and confirm that it still prints cross-check: balances while charging 47 nothing and ignoring 48 entirely. Then replace the fake cross-check with the two real ones: an array_intersect_key() test that every collection has a deposit, and an array_key_exists() guard in bill() that throws on an unknown size class.

  1. Extract groupBy(). Write

function groupBy(array $rows, string $key): array returning a map from each distinct value of that key to the list of rows carrying it, then use it to replace both the $byOwner line and the three $bySize accumulator lines. Decide deliberately whether the returned inner arrays are lists, and state why.

  1. Test the stability claim. Build a list of twenty rows where the sort key

takes only three distinct values, sort it with usort() on that key alone, and check that rows with equal keys came out in their original order. Then add a secondary key to the comparison and confirm the output changes only where you expected it to.