Today's puzzle · #1 · PHP
foreach by reference, then by value
Friday, 13 November 2026 · One try
What does this code print?
$a = [1, 2, 3];
foreach ($a as &$v) {}
foreach ($a as $v) {}
echo implode(',', $a);
Correct! Not this time. The answer: 1,2,2
After the first loop $v is still a reference to the last element. The second loop assigns each value to $v, so it keeps overwriting $a[2]: with 1, then 2, then 2. Call unset($v) after a by-reference loop.