In this chapter
We'll learn how to unpack an array into variables with destructuring — [$a, $b] = and ["time" => $time] = — how the spread operator ... copies arrays into a new one and unpacks them into function arguments, and how references (&) let a foreach loop change the array it walks through — plus the classic bug they leave behind.
The Problem in Real Life
Olivia wants every price 10% higher before launch. Mia writes a loop over the services list — each service an array with a name and a price — and multiplies each price by 1.1 inside the loop.
She prints the services afterwards. Haircut, £25. Beard trim, £10. Every price is exactly as before. No error, no warning.
The loop ran three times and changed three prices. Where did the changes go?
Mia
Working on a Copy vs. Working on the Array
foreach gives you copies
Inside foreach ($services as $service), $service is a copy. Changing it changes nothing in $services.
Unpacking values
$booking["time"], $booking["customer"], $booking["service"] … destructuring takes them out in one line.
References stay connected
A & makes a variable another name for the array item — and it stays that way after the loop.
Destructuring, Spread and Unpacking
Moving values in and out of arrays: this chapter covers three short pieces of syntax that save a lot of lines, and one that changes how a loop works:
- Destructuring:
[$time, $customer] = $pair;takes values out of an array into variables. - Spread:
[...$ben, ...$leo]copies the items of arrays into a new array, andf(...$args)passes them as arguments. - References:
foreach ($services as &$service)makes the loop variable another name for the real item, so changes stick.
Destructuring a list: [$time, $customer] = ["9:30", "Clare Lefèvre"]; puts item 0 into $time and item 1 into $customer. This is called destructuring. The old form, list($time, $customer) = ..., does the same. Leave a place empty to skip an item: [, $customer] = $pair;. Destructuring also swaps two variables without a third one: [$a, $b] = [$b, $a];. If the array has fewer items than you ask for, the missing variables get null with a warning.
<?php$pair = ["9:30", "Clare Lefèvre"];[$time, $customer] = $pair;echo "$customer at $time\n"; // Clare Lefèvre at 9:30[, $onlyName] = $pair; // skip item 0echo $onlyName, "\n"; // Clare Lefèvre$a = "Ben";$b = "Leo";[$a, $b] = [$b, $a]; // swapecho "$a $b\n"; // Leo Ben
Destructuring by key: for associative arrays, name the keys: ["time" => $time, "customer" => $customer] = $booking;. Order doesn't matter, and you only take the keys you need. It works in foreach too, which reads very well for a list of records: foreach ($day as ["time" => $time, "customer" => $customer]). And you can nest: [[$first], $rest] = ....
<?php$booking = ["time" => "9:30", "customer" => "Clare Lefèvre", "service" => "Haircut"];["customer" => $customer, "time" => $time] = $booking; // any order, only what you needecho "$customer at $time\n"; // Clare Lefèvre at 9:30$day = [["time" => "9:00", "customer" => "Tom Hart"],["time" => "9:30", "customer" => "Clare Lefèvre"],];foreach ($day as ["time" => $time, "customer" => $customer]) {echo "$time $customer\n";}// 9:00 Tom Hart// 9:30 Clare Lefèvre
The spread operator: inside an array literal, ...$array copies all the items of another array into the new one: [...$ben, ...$leo] is one list with everyone's bookings. Since PHP 8.1, arrays with string keys can be spread too; a later string key overwrites an earlier one, while integer keys are renumbered. In a function call, ...$args unpacks an array into separate arguments: max(...$prices) is max(25, 10, 2.5). With string keys, they become named arguments (Act 09).
<?php$ben = ["9:00", "10:00"];$leo = ["9:30"];$all = [...$ben, ...$leo, "11:00"];echo implode(" ", $all), "\n"; // 9:00 10:00 9:30 11:00$base = ["Haircut" => 25, "Beard trim" => 10];$saturday = [...$base, "Haircut" => 27]; // string keys: the later one winsprint_r($saturday);// Array// (// [Haircut] => 27// [Beard trim] => 10// )$prices = [25, 10, 2.5];echo max(...$prices), "\n"; // 25: max(25, 10, 2.5)
Why the prices didn't change: in foreach ($services as $service), PHP puts a copy of each item into $service. Changing the copy changes nothing in $services. That's what happened to Mia's 10%. There are two fixes. Write through the key: foreach ($services as $i => $service) { $services[$i]["price"] = ...; }. Or use a reference: foreach ($services as &$service). The & (Act 03) makes $service another name for the real item, so $service["price"] *= 1.1 changes the array itself.
<?php$services = [["name" => "Haircut", "price" => 25],["name" => "Beard trim", "price" => 10],];foreach ($services as $service) {$service["price"] *= 1.1; // changes the copy only}echo $services[0]["price"], "\n"; // 25: unchangedforeach ($services as $i => $service) {$services[$i]["price"] = round($service["price"] * 1.1, 2); // fix 1: write through the key}echo $services[0]["price"], "\n"; // 27.5
<?php$services = [["name" => "Haircut", "price" => 25],["name" => "Beard trim", "price" => 10],];foreach ($services as &$service) {$service["price"] = round($service["price"] * 1.1, 2); // changes the real item}unset($service); // end the reference: always do thisecho $services[0]["price"], " ", $services[1]["price"], "\n"; // 27.5 11
The reference trap: a reference doesn't end when the loop ends. After foreach ($services as &$service), $service is still another name for the last item. If a later loop uses the same name without & — foreach ($services as $service) — every round writes the current item into that last item. The list ends up with the last item overwritten, as the code below shows. The rule: right after a loop with &, write unset($service);. Or avoid the reference completely and build a new array, which is what array_map() in the next chapter does. The table below sums up the syntax.
| Syntax | Example | Does |
|---|---|---|
| List destructuring | [$time, $customer] = $pair; | Item 0 into $time, item 1 into $customer |
| Skip an item | [, $customer] = $pair; | Takes only item 1 |
| Keyed destructuring | ["time" => $t] = $booking; | Takes the value of the key "time" |
| In foreach | foreach ($day as ["time" => $t]) | Unpacks every record |
| Spread into an array | [...$ben, ...$leo] | One new array with all the items |
| Unpack into arguments | max(...$prices) | Each item becomes an argument |
| Loop by reference | foreach ($a as &$item) { } unset($item); | Changes the real items |
<?php$times = ["9:00", "9:30", "10:00"];foreach ($times as &$time) {$time = "Sat $time";}// no unset($time) here!foreach ($times as $time) { // same name, no &: writes into the last item}print_r($times);// Array// (// [0] => Sat 9:00// [1] => Sat 9:30// [2] => Sat 9:30// )
Key Takeaway
[$a, $b] = $list and ["key" => $var] = $record unpack arrays into variables, also inside foreach. ...$array spreads items into a new array or into function arguments. foreach gives you a copy of each item, so changes are lost — write through the key, or loop by reference with &$item and unset($item) right after the loop, or build a new array.
Why This Matters
A price change that silently does nothing is worse than an error: it looks done, and the old prices go live. Knowing that foreach hands you copies — and how to change the real items — prevents a whole family of "it ran, but nothing changed" bugs.
Destructuring and spread make everyday code shorter and clearer: unpacking a booking into named variables, joining two barbers' lists into one. You'll see them everywhere in modern PHP and Laravel code.
The new prices stick, and Mia has learned to write unset() after every & loop. Now the day view itself. Olivia wants three things from the same list of bookings: hide the cancelled ones, show each price with a £, and a total at the bottom. Mia writes three foreach loops — and the first booking after filtering is missing again. That's the next chapter: map, filter and reduce.
