|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #50485 foreach by reference followed by foreach not by reference - Unexpected Results
Submitted: 2009-12-16 00:33 UTC Modified: 2009-12-16 00:37 UTC
From: plasticlobster at gmail dot com Assigned:
Status: Not a bug Package: Arrays related
PHP Version: 5.2.11 OS: Debian
Private report: No CVE-ID: None
 [2009-12-16 00:33 UTC] plasticlobster at gmail dot com
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) {

foreach ($foo as $key => $val) {
   echo $val;

Expected result:
Expected result is:

Actual result:
Actual Result is:

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.


Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2009-12-16 00:37 UTC]
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.
 [2015-01-01 20:25 UTC] chealer at gmail dot com
The problematic behavior behind this issue is being tracked in #62132.
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sat Jul 13 08:01:29 2024 UTC