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. 1,2,3
  2. 1,2,2
  3. 3,3,3
  4. 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.