Skip to content

Strange and confusing behaviour of foreach with iteration by reference #20327

Closed as not planned

Description

@phront

Description

The following code:

<?php

$aaa = [[1,2,3,4]];
$i = 5;
foreach ($aaa as &$aa) {
	foreach ($aa as &$a) {
		$a = $i;
		$i--;
	}
}

var_dump ($aaa);
foreach ($aaa as &$aa) {
	foreach ($aa as $a) {
	}
}
var_dump ($aaa);

Resulted in this output:

array(1) {
  [0]=>
  &array(4) {
    [0]=>
    int(5)
    [1]=>
    int(4)
    [2]=>
    int(3)
    [3]=>
    &int(2)
  }
}
array(1) {
  [0]=>
  &array(4) {
    [0]=>
    int(5)
    [1]=>
    int(4)
    [2]=>
    int(3)
    [3]=>
    &int(3)
  }
}

But I expected at least this output instead:

array(1) {
  [0]=>
  &array(4) {
    [0]=>
    int(5)
    [1]=>
    int(4)
    [2]=>
    int(3)
    [3]=>
    int(2)
  }
}
array(1) {
  [0]=>
  &array(4) {
    [0]=>
    int(5)
    [1]=>
    int(4)
    [2]=>
    int(3)
    [3]=>
    int(2)
  }
}

Played the script with different versions on
https://onlinephp.io?s=s7EvyCjg5eLlUklMTFSwVYiONtQx0jHWMYmNtQYKZgKFTIGMtPyi1MTkDAUNsLLEYgU1IENToZqXixNZCioDkeBUARmokmkNZmfq6oIYtbxctSDryhKL4lNKcwsgJmqSZgXMBohhmEaBoIKCAogCAA%2C%2C&v=8.4.10

PHP Version

PHP Version => 8.4.10
Zend Engine v4.4.10, Copyright (c) Zend Technologies

Build Date => Jul 13 2025 00:21:23
Build System => Linux  4.14.290-217.505.amzn2.x86_64 #1 SMP Wed Aug 10 09:52:16 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux

Operating System

Linux 5.10.214-202.855.amzn2.x86_64 #1 SMP Tue Apr 9 06:57:12 UTC 2024 x86_64

Activity

  1. iluuu1994 commented on Oct 29, 2025

    @iluuu1994
    Member

    Common pitfall. https://3v4l.org/qRiSf You need to unset $a after the foreach. This is not a bug, though a footgun that cannot easily be changed. You'll find various reports in the bug tracker.

  2. marked bug in all 8.x versions #20396 as a duplicate of this issue on Nov 5, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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