Bug #67419 [Opn->Nab]: foreach access the array problem

From: Date: Wed, 11 Jun 2014 04:28:03 +0000
Subject: Bug #67419 [Opn->Nab]: foreach access the array problem
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-186148@lists.php.net to get a copy of this message
Edit report at https://bugs.php.net/bug.php?id=67419&edit=1 ID: 67419 Updated by: requinix@php.net Reported by: rilyu at sina dot com Summary: foreach access the array problem -Status: Open +Status: Not a bug Type: Bug Package: Arrays related Operating System: Windows 7 PHP Version: 5.5.13 Block user comment: N Private report: N New Comment: 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. Previous Comments: ------------------------------------------------------------------------ [2014-06-11 03:38:51] 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) } ------------------------------------------------------------------------ -- Edit this bug report at https://bugs.php.net/bug.php?id=67419&edit=1

« previous php.bugs (#186148) next »