php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #50582 Incorrect foreach iteration by value after iteration by reference
Submitted: 2009-12-26 22:48 UTC Modified: 2009-12-27 04:52 UTC
From: mwacker at cornellsun dot com Assigned:
Status: Not a bug Package: Arrays related
PHP Version: 5.3.1 OS: Ubuntu 9.10
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: mwacker at cornellsun dot com
New email:
PHP Version: OS:

 

 [2009-12-26 22:48 UTC] 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

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2009-12-26 23:25 UTC] 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-27 04:52 UTC] 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.
 [2014-03-21 08:12 UTC] tri at iki dot fi
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.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sun Dec 22 02:01:28 2024 UTC