php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #65034 Problem with array behavior after using reference
Submitted: 2013-06-13 20:51 UTC Modified: 2013-06-13 21:00 UTC
From: shark555 at gmail dot com Assigned:
Status: Not a bug Package: *General Issues
PHP Version: Irrelevant OS: Linux
Private report: No CVE-ID: None
 [2013-06-13 20:51 UTC] shark555 at gmail dot com
Description:
------------
After using same name in first and third foreach script returns wrong result.
Last element is changed to one just before it.
As we can see it only happens if name of reference and variable used later in 
foreach is the same("product"). What is worse it affects every next iteration. 
After that it doesn't matter what is the name of helper variable.

Problem affects PHP versions: 5.2, 5.3 and 5.4 at least.
Different compilations by different people and companies.


Possibly related to: https://bugs.php.net/bug.php?id=60450&edit=2

Test script:
---------------
$products = array(
    array('id'=>1,'name'=>'Cheese'),
    array('id'=>2,'name'=>'Cake'),
    array('id'=>3,'name'=>'Fish'),
    array('id'=>4,'name'=>'Soup'),
    array('id'=>5,'name'=>'Pasta'),
);

$i = 0;
foreach($products as &$product) {
    $product['name'] = $product['name'].$i;
    $i++;
}

foreach($products as $p) {
    echo $p['name'];
    echo "\n";
}

echo "\n";

foreach($products as $product) {
    echo $product['name'];
    echo "\n";
}

echo "\n";

foreach($products as $p) {
    echo $p['name'];
    echo "\n";
}


Expected result:
----------------
Cheese0
Cake1
Fish2
Soup3
Pasta4

Cheese0
Cake1
Fish2
Soup3
Pasta4

Cheese0
Cake1
Fish2
Soup3
Pasta4

Actual result:
--------------
Cheese0
Cake1
Fish2
Soup3
Pasta4

Cheese0
Cake1
Fish2
Soup3
Soup3

Cheese0
Cake1
Fish2
Soup3
Soup3


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2013-06-13 21:00 UTC] aharvey@php.net
-Status: Open +Status: Not a bug
 [2013-06-13 21:00 UTC] aharvey@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

Per the warning at http://php.net/manual/en/control-structures.foreach.php, you 
should always unset() the iterator reference after the foreach to avoid this sort 
of issue, since PHP doesn't have block scope.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Mon May 27 10:01:30 2024 UTC