#36240 [Com]: foreach($arr as $k => &$v) corrupts array on second iteration

From: Date: Wed, 01 Feb 2006 07:20:40 +0000
Subject: #36240 [Com]: foreach($arr as $k => &$v) corrupts array on second iteration
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-92742@lists.php.net to get a copy of this message
ID: 36240 Comment by: judas dot iscariote at gmail dot com Reported By: dshadow at zort dot net Status: Open Bug Type: Scripting Engine problem Operating System: Mac OS X PHP Version: 5.1.2 New Comment: BOGUS. read bug 29992 Previous Comments: ------------------------------------------------------------------------ [2006-02-01 06:35:00] dshadow at zort dot net Description: ------------ After using foreach($arr as $k => &$v) to modify the $arr, iterating again using the same variable $v causes the array to be altered unexpectedly. Adding an unset($v) between the two foreach loops, or using a different variable on the second foreach loop works around the problem. Reproduce code: --------------- <? $arr = array( 'one' => 1, 'two' => 2, 'three' => 3, ); foreach($arr as $k => &$v) if($v == 1) $v = 'meh'; print_r($arr); foreach($arr as $k => $v) ; print_r($arr); Expected result: ---------------- The code above should not cause the $arr to be modified by running the second foreach loop. Actual result: -------------- The code above outputs the following: Array ( [one] => meh [two] => 2 [three] => 3 ) Array ( [one] => meh [two] => 2 [three] => 2 ) ------------------------------------------------------------------------ -- Edit this bug report at http://bugs.php.net/?id=36240&edit=1

« previous php.bugs (#92742) next »