php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #67419 foreach access the array problem
Submitted: 2014-06-11 03:38 UTC Modified: 2014-06-11 04:28 UTC
From: rilyu at sina dot com Assigned:
Status: Not a bug Package: Arrays related
PHP Version: 5.5.13 OS: Windows 7
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: rilyu at sina dot com
New email:
PHP Version: OS:

 

 [2014-06-11 03:38 UTC] rilyu at sina dot com
Description:
------------
Access the array using foreach, the first time is

  foreach($list as &$row)

for the second time is

  foreach($list as $row)

this time $row values ​​are incorrect

Test script:
---------------
$list = array(
  array("x" => 1),
  array("x" => 3)
);

foreach($list as &$row)
{
  if ($row["x"] == 1) $row["y"] = 10;
}

foreach($list as $row)
{
  var_dump($row);
}


Expected result:
----------------
array(2) {
  ["x"]=>
  int(1)
  ["y"]=>
  int(10)
}
array(1) {
  ["x"]=>
  int(3)
}


Actual result:
--------------
array(2) {
  ["x"]=>
  int(1)
  ["y"]=>
  int(10)
}
array(2) {
  ["x"]=>
  int(1)
  ["y"]=>
  int(10)
}


Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2014-06-11 04:28 UTC] requinix@php.net
-Status: Open +Status: Not a bug
 [2014-06-11 04:28 UTC] requinix@php.net
That's references for you. After the first loop ends $row will still be a reference to the last element in the array, so when the second loop sets $row to each of the values it finds in the array, the referenced value gets updated.

unset($row) after the first loop. Better yet, don't use references where you don't need them.
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Wed Jul 02 11:01:36 2025 UTC