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
 [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-2021 The PHP Group
All rights reserved.
Last updated: Wed Oct 20 14:03:39 2021 UTC