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
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
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

Add a Patch

Pull Requests

Add a Pull Request

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-2024 The PHP Group
All rights reserved.
Last updated: Fri May 17 12:01:32 2024 UTC