php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #52418 foreach returns inconsistent results
Submitted: 2010-07-23 15:20 UTC Modified: 2010-07-23 15:27 UTC
From: joe dot vallet at gmail dot com Assigned:
Status: Not a bug Package: *Programming Data Structures
PHP Version: 5.3.3 OS: Linux
Private report: No CVE-ID: None
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: joe dot vallet at gmail dot com
New email:
PHP Version: OS:

 

 [2010-07-23 15:20 UTC] joe dot vallet at gmail dot com
Description:
------------
I make a loop with a "foreach" and each item is passed by reference.
After what I make another loop on the same array with the same item var name, but not by reference this time.
Then the last value of the array is replaced by next to last one.

Test script:
---------------
<?php
$idList = array(42, 52, 101010);

foreach($idList as &$id)
{};
print_r($idList);
// => Array ( [0] => 42 [1] => 52 [2] => 101010 )

foreach($idList as $id)
{};
print_r($idList);
// => Array ( [0] => 42 [1] => 52 [2] => 52 )
//                                       ==
?>


Expected result:
----------------
Array ( [0] => 42 [1] => 52 [2] => 101010 )
Array ( [0] => 42 [1] => 52 [2] => 101010 )

Actual result:
--------------
Array ( [0] => 42 [1] => 52 [2] => 101010 )
Array ( [0] => 42 [1] => 52 [2] => 52)

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2010-07-23 15:27 UTC] aharvey@php.net
-Status: Open +Status: Bogus
 [2010-07-23 15:27 UTC] aharvey@php.net
Foreach has some unusual semantics when it's used with a reference due to the lack of block scope in PHP, hence the warning at http://au2.php.net/manual/en/control-structures.foreach.php advising against the reuse of a referenced iterator variable.

A number of bugs have previously been opened about this behaviour, including most recently bug #51409, bug #50582 and bug #50485 (and probably many, many others going further back). This behaviour won't be changed, due to backward compatibility concerns.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Fri Mar 29 06:01:29 2024 UTC