Bug #50582 [Com]: Incorrect foreach iteration by value after iteration by reference

From: Date: Fri, 21 Mar 2014 08:12:02 +0000
Subject: Bug #50582 [Com]: Incorrect foreach iteration by value after iteration by reference
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-184848@lists.php.net to get a copy of this message
Edit report at https://bugs.php.net/bug.php?id=50582&edit=1 ID: 50582 Comment by: tri at iki dot fi Reported by: mwacker at cornellsun dot com Summary: Incorrect foreach iteration by value after iteration by reference Status: Not a bug Type: Bug Package: Arrays related Operating System: Ubuntu 9.10 PHP Version: 5.3.1 Block user comment: N Private report: N New Comment: In my opinion it is definitely a bug. I can understand why it can be called a feature, but the foreach semantics should be defined so that loop variable is unset (meaningful only if the value happens to be a reference) before the loop construct starts to assign values to it. This is source of weird and subtle bugs. Previous Comments: ------------------------------------------------------------------------ [2009-12-27 04:52:40] rasmus@php.net It doesn't act weird. There is no block scope in PHP, so at the end of the first loop $i is a reference to the last element of $ii and in the second loop you are now assigning values to that reference which means you are overwriting the 3rd element of $ii each time through the loop. That of course means that once you get to the 3rd element of $ii it is no longer 3 and you see the last value assigned to it, which was 2. ------------------------------------------------------------------------ [2009-12-26 23:25:34] pierrick@php.net Thank you for taking the time to write to us, but this is not a bug. Please double-check the documentation available at http://www.php.net/manual/ and the instructions on how to report a bug at http://bugs.php.net/how-to-report.php ------------------------------------------------------------------------ [2009-12-26 22:48:18] mwacker at cornellsun dot com Description: ------------ A variable acts weird when it is used as a reference variable inside a foreach loop and then as a regular variable inside a foreach loop. (Originally seen in 5.2.10-2ubuntu6.3, repro'd in a fresh 5.3.1 install) Reproduce code: --------------- $ii = array(1, 2, 3); foreach ($ii as &$i) echo $i; foreach ($ii as $i) echo $i; Expected result: ---------------- 123123 Actual result: -------------- 123122 ------------------------------------------------------------------------ -- Edit this bug report at https://bugs.php.net/bug.php?id=50582&edit=1

« previous php.bugs (#184848) next »