#50582 [Bgs]: Incorrect foreach iteration by value after iteration by reference
| From: | rasmus@php.net | Date: | Sun, 27 Dec 2009 04:52:41 +0000 |
| Subject: | #50582 [Bgs]: Incorrect foreach iteration by value after iteration by reference | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-146131@lists.php.net to get a copy of this message | ||
ID: 50582
Updated by: rasmus@php.net
Reported By: mwacker at cornellsun dot com
Status: Bogus
Bug Type: Arrays related
Operating System: Ubuntu 9.10
PHP Version: 5.3.1
New Comment:
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.
Previous Comments:
------------------------------------------------------------------------
[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 http://bugs.php.net/?id=50582&edit=1