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

From: Date: Wed, 01 Feb 2006 05:35:04 +0000
Subject: #36240 [NEW]: foreach($arr as $k => &$v) corrupts array on second iteration
Groups: php.bugs 
Request: Send a blank email to php-bugs+get-92741@lists.php.net to get a copy of this message
From: dshadow at zort dot net Operating system: Mac OS X PHP version: 5.1.2 PHP Bug Type: Scripting Engine problem Bug description: foreach($arr as $k => &$v) corrupts array on second iteration 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 bug report at http://bugs.php.net/?id=36240&edit=1 -- Try a CVS snapshot (PHP 4.4): http://bugs.php.net/fix.php?id=36240&r=trysnapshot44 Try a CVS snapshot (PHP 5.1): http://bugs.php.net/fix.php?id=36240&r=trysnapshot51 Try a CVS snapshot (PHP 6.0): http://bugs.php.net/fix.php?id=36240&r=trysnapshot60 Fixed in CVS: http://bugs.php.net/fix.php?id=36240&r=fixedcvs Fixed in release: http://bugs.php.net/fix.php?id=36240&r=alreadyfixed Need backtrace: http://bugs.php.net/fix.php?id=36240&r=needtrace Need Reproduce Script: http://bugs.php.net/fix.php?id=36240&r=needscript Try newer version: http://bugs.php.net/fix.php?id=36240&r=oldversion Not developer issue: http://bugs.php.net/fix.php?id=36240&r=support Expected behavior: http://bugs.php.net/fix.php?id=36240&r=notwrong Not enough info: http://bugs.php.net/fix.php?id=36240&r=notenoughinfo Submitted twice: http://bugs.php.net/fix.php?id=36240&r=submittedtwice register_globals: http://bugs.php.net/fix.php?id=36240&r=globals PHP 3 support discontinued: http://bugs.php.net/fix.php?id=36240&r=php3 Daylight Savings: http://bugs.php.net/fix.php?id=36240&r=dst IIS Stability: http://bugs.php.net/fix.php?id=36240&r=isapi Install GNU Sed: http://bugs.php.net/fix.php?id=36240&r=gnused Floating point limitations: http://bugs.php.net/fix.php?id=36240&r=float No Zend Extensions: http://bugs.php.net/fix.php?id=36240&r=nozend MySQL Configuration Error: http://bugs.php.net/fix.php?id=36240&r=mysqlcfg

« previous php.bugs (#92741) next »