php-src icon indicating copy to clipboard operation
php-src copied to clipboard

Issue with foreach when used with reference "&" and reusing the same variable

Open djidel opened this issue 10 months ago • 1 comments

Description

The following code:

<?php
$a = [1,2,3];
foreach($a as &$i) $i++;
var_export($a);
foreach($a as $i) $b = $i+1;
var_export($a);

Resulted in this output:

array (
  0 => 2,
  1 => 3,
  2 => 4,
)array (
  0 => 2,
  1 => 3,
  2 => 3,
)

But I expected this output instead:

array (
  0 => 2,
  1 => 3,
  2 => 4,
)array (
  0 => 2,
  1 => 3,
  2 => 4,
)

PHP Version

Tested on 8.3.21, 8.4.10, 8.2.29, 8.1.33, 8.2.20:

Operating System

No response

djidel avatar Jan 26 '26 00:01 djidel

This is caused by the side effects of foreach($a as $i) $b = $i+1; Given that $b is not used, this is effectively foreach($a as $i) {} if we desugar this, we get the overall to be clearer - because $i is still a reference to $a[2] at the end of the first foreach, it remains bound afterwards and continues updating $a[2]

<?php

$a = [1,2,3];
foreach($a as &$i) $i++;
var_export($a);

// $a = [2, 3, 4]
// $i is a reference to $a[2]
$i = $a[0]; // $a[2] = $a[0], $a is now [2, 3, 2]
$i = $a[1]; // $a[2] = $a[1], $a is now [2, 3, 3]
$i = $a[2]; // $a[2] = $a[2], $a stays [2, 3, 3]
var_export($a);

This is the expected behavior of having a reference variable in the first foreach

DanielEScherzer avatar Jan 26 '26 08:01 DanielEScherzer