php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #54351 foreach loop corrupts data
Submitted: 2011-03-22 14:41 UTC Modified: 2011-03-31 12:18 UTC
From: drake at jetcode dot ru Assigned:
Status: Not a bug Package: *General Issues
PHP Version: Irrelevant OS: CentOS
Private report: No CVE-ID: None
View Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
If you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: drake at jetcode dot ru
New email:
PHP Version: OS:

 

 [2011-03-22 14:41 UTC] drake at jetcode dot ru
Description:
------------
Affected PHP versions:

5.3.5
5.3.5
5.2.9

Bug reveals only in case when loop variables are SAME and second loop variable is NOT passed by reference.







Test script:
---------------
$items = array
(
    array('id' => 1),
    array('id' => 2),
    array('id' => 3),
    array('id' => 4)
);
 
foreach ( $items as &$item )
{
    $item['foo'] = 'bar';
}
 
// Expected $items id's: 1, 2, 3, 4
// Actualy: 1, 2, 3, 4
 
foreach ( $items as $item )
{
    // do nothing
}

// Expected $items id's: 1, 2, 3, 4
// Actualy: 1, 2, 3, 3 <-- BUG!


Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2011-03-22 14:46 UTC] aharvey@php.net
-Status: Open +Status: Bogus
 [2011-03-22 14:46 UTC] aharvey@php.net
This is documented behaviour: foreach with references doesn't behave
as you'd expect. Note the warning at http://php.net/foreach about this.
 
PHP Copyright © 2001-2026 The PHP Group
All rights reserved.
Last updated: Sun May 24 09:00:01 2026 UTC