Skip to content

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.

Past puzzles

Get new articles in your inbox

Practical tutorials and deep dives, about once a week. No spam, unsubscribe anytime.

Privacy policy

Add DEV Talk to your Home Screen

  1. 1 Tap the Share button in Safari's toolbar.
  2. 2 Scroll down and tap Add to Home Screen.
  3. 3 Tap Add. Open it from the Home Screen to read like an app and to turn on notifications with the bell.

We use cookies to improve your experience and analyze traffic. By continuing, you agree to our Privacy Policy.