#43988 [NEW]: Problems with foreach'ing on arrays with referenced element

From: Date: Thu, 31 Jan 2008 03:28:11 +0000
Subject: #43988 [NEW]: Problems with foreach'ing on arrays with referenced element
Groups: php.bugs 
Request: Send a blank email to php-bugs+get-121809@lists.php.net to get a copy of this message
From: claim at interia dot pl Operating system: Linux 2.6.23 PHP version: 5.2.5 PHP Bug Type: Unknown/Other Function Bug description: Problems with foreach'ing on arrays with referenced element Description: ------------ The problem is that when you reference an array element (say, n) and then use the same name (as the reference) as the current element value alias inside foreach, two things happen: 1. inside the foreach body the n element is replaced with the n-1 element; 2. and after the foreach run the n element is replaced with the last array element. Reproduce code: --------------- <?php $arr = array(); for ($i = 0; $i < 4; ++$i) { $arr[$i] = $i; } $el = &$arr[2]; print_r($arr); foreach ($arr as $el) { echo "el: $el\n"; } print_r($arr); ?> Expected result: ---------------- Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 ) el: 0 el: 1 el: 2 el: 3 Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 ) Actual result: -------------- Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 ) el: 0 el: 1 el: 1 el: 3 Array ( [0] => 0 [1] => 1 [2] => 3 [3] => 3 ) -- Edit bug report at http://bugs.php.net/?id=43988&edit=1 -- Try a CVS snapshot (PHP 4.4): http://bugs.php.net/fix.php?id=43988&r=trysnapshot44 Try a CVS snapshot (PHP 5.2): http://bugs.php.net/fix.php?id=43988&r=trysnapshot52 Try a CVS snapshot (PHP 5.3): http://bugs.php.net/fix.php?id=43988&r=trysnapshot53 Try a CVS snapshot (PHP 6.0): http://bugs.php.net/fix.php?id=43988&r=trysnapshot60 Fixed in CVS: http://bugs.php.net/fix.php?id=43988&r=fixedcvs Fixed in release: http://bugs.php.net/fix.php?id=43988&r=alreadyfixed Need backtrace: http://bugs.php.net/fix.php?id=43988&r=needtrace Need Reproduce Script: http://bugs.php.net/fix.php?id=43988&r=needscript Try newer version: http://bugs.php.net/fix.php?id=43988&r=oldversion Not developer issue: http://bugs.php.net/fix.php?id=43988&r=support Expected behavior: http://bugs.php.net/fix.php?id=43988&r=notwrong Not enough info: http://bugs.php.net/fix.php?id=43988&r=notenoughinfo Submitted twice: http://bugs.php.net/fix.php?id=43988&r=submittedtwice register_globals: http://bugs.php.net/fix.php?id=43988&r=globals PHP 3 support discontinued: http://bugs.php.net/fix.php?id=43988&r=php3 Daylight Savings: http://bugs.php.net/fix.php?id=43988&r=dst IIS Stability: http://bugs.php.net/fix.php?id=43988&r=isapi Install GNU Sed: http://bugs.php.net/fix.php?id=43988&r=gnused Floating point limitations: http://bugs.php.net/fix.php?id=43988&r=float No Zend Extensions: http://bugs.php.net/fix.php?id=43988&r=nozend MySQL Configuration Error: http://bugs.php.net/fix.php?id=43988&r=mysqlcfg

« previous php.bugs (#121809) next »