Predict the output · PHP
foreach by Reference Leftover
Medium Predict the output Seen at Automattic, Mollie
What does this print?
What does this print?
<?php
$items = [1, 2, 3];
foreach ($items as &$item) {
}
foreach ($items as $item) {
}
echo implode(',', $items);
1,2,3
1,2,2
3,3,3
1,1,1
Check your answer
Loading the editor… (JavaScript is required to run code in your browser.)
Solution
Show the answer
The output is:
1,2,2
After the first loop, $item is still a reference to the last element ($items[2]). The second loop assigns each element to $item — i.e. writes into $items[2]: it becomes 1, then 2, then (reading itself) stays 2.
Always unset($item) after a by-reference foreach, or avoid references and use array_map/keys.
More Gotchas problems
- var in a Loop with setTimeout · Easy
- Microtasks vs Macrotasks · Medium
- Type Coercion Surprises · Medium
- Numeric Enums at Runtime · Medium
- Type Assertions Don't Convert · Easy
- readonly and as const at Runtime · Medium