PHP Array Destructuring Goes Further Than You Think
Most PHP developers know [$a, $b] = $pair; and stop there. The destructuring syntax handles keys, nesting and loops - and the loop form is where it turns genuinely load-bearing.
Keyed destructuring: rows into variables
['id' => $id, 'email' => $email] = $row;
// Order doesn't matter, extra keys are ignored, missing keys warn (and yield null)
['total' => $total] = $order;
Pull exactly the fields you need from an associative array, named at the point of use. Compare $row['email'] sprinkled eight times through a function versus one destructure at the top - the variable names become documentation of what the function actually consumes.
foreach destructuring: the daily driver
foreach ($orders as ['id' => $id, 'total' => $total, 'email' => $email]) {
printf("#%d %s %s\n", $id, money($total), $email);
}
// Positional works too - great for coordinate pairs, [key, label] tuples
foreach ($menuItems as [$url, $label]) {
echo "<a href=\"$url\">$label</a>";
}
This is the feature that makes PDO's default fetch arrays pleasant to consume without an ORM: query, then destructure per row, and the loop body reads like it's working with real variables because it is.
Nesting, swaps and defaults
// Nested extraction - config trees, decoded JSON
['db' => ['host' => $host, 'port' => $port]] = $config;
// The swap - no $tmp
[$a, $b] = [$b, $a];
// Skipping positions
[, , $third] = $csvRow;
// "Defaults" via union (destructuring itself has no default syntax)
['page' => $page, 'per' => $per] = $_GET + ['page' => 1, 'per' => 20];
That last idiom deserves its fifteen seconds: the + operator keeps left-side keys and fills gaps from the right - array union as a defaults mechanism, then destructure the merged result. Two lines, and query-param handling stops being a wall of ?? expressions. (Type-cast after, of course - everything in $_GET is a string.)
Boundaries and taste
- Missing keys emit a warning and assign null - fine for internal data you control, wrong for user input. Validate first; destructure trusted shapes.
- References work:
foreach ($rows as ['id' => $id, 'count' => &$count])- use sparingly, as ever with references. - Once a shape is destructured in three places, that's the signal it wants to be a readonly DTO instead - destructuring is the gateway drug to real value objects, and that's a compliment.
list() and [] are identical; use the brackets. Small syntax, big legibility - the difference between code that describes shapes and code that indexes into mysteries.
Full-stack web developer sharing practical tutorials and building tools that ship.
Got something on your mind?
My inbox is open - no forms disappearing into the void here.
- Just say hello Found a tutorial useful? Spotted a mistake? Tell me.
- Hire me for a project Have something custom in mind? Let's talk scope and timelines.
- Product support Bought something here? I'll help you get it running.
I usually reply within 1-2 business days.