Bug #50485 [Com]: foreach by reference followed by foreach not by reference - Unexpected Results
| From: | chealer at gmail dot com | Date: | Thu, 01 Jan 2015 20:25:49 +0000 |
| Subject: | Bug #50485 [Com]: foreach by reference followed by foreach not by reference - Unexpected Results | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-189584@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=50485&edit=1
ID: 50485
Comment by: chealer at gmail dot com
Reported by: plasticlobster at gmail dot com
Summary: foreach by reference followed by foreach not by
reference - Unexpected Results
Status: Not a bug
Type: Bug
Package: Arrays related
Operating System: Debian
PHP Version: 5.2.11
Block user comment: N
Private report: N
New Comment:
The problematic behavior behind this issue is being tracked in #62132.
Previous Comments:
------------------------------------------------------------------------
[2009-12-16 00:37:36] rasmus@php.net
The current implementation is consistent. Granted, not very useful,
but it would be inconsistent to arbitrarily break the reference here.
PHP has no block scope, and breaking the reference would introduce a
special-case block-scope here.
------------------------------------------------------------------------
[2009-12-16 00:33:08] plasticlobster at gmail dot com
Description:
------------
Running two foreach loops on different parts of the same array, one by reference, one not causes
unexpected results.
Reproduce code:
---------------
$foo = array(1,2,3,4,5);
foreach ($foo as $key => &$val) {
$val++;
}
foreach ($foo as $key => $val) {
echo $val;
}
Expected result:
----------------
Expected result is:
23456
Actual result:
--------------
Actual Result is:
23455
This is duplicate of bug #47388 which was dismissed without investigation. The problem here is
two-fold:
1. The scope of foreach should not extend beyond a foreach loop.
2. $val should be re-initialized as a VALUE, not a REFERENCE.
It looks like the second foreach is doing something comparable to $val = $foo[0]. It should be
calling unset($val) prior to assigning anything to it. This is like going into a for loop and
finding out that your explicit value for the incrementor variable didn't get set because you
had used it in a previous for loop.
I would have commented on #47388, but comments were disabled as it was abruptly closed.
When deciding whether or not to accept this as a bug, please keep in mind that the current
implementation serves no programmatic purpose and that the proposed implementation is not only more
intuitive/expected, but also serves a purpose.
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=50485&edit=1