Skip to content

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

@djidel

Description

@djidel

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions