php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #66859 Variable re-use in for loop causes corruption
Submitted: 2014-03-09 06:14 UTC Modified: 2014-03-10 01:00 UTC
Votes:1
Avg. Score:4.0 ± 0.0
Reproduced:1 of 1 (100.0%)
Same Version:1 (100.0%)
Same OS:1 (100.0%)
From: jake_hotson at hotmail dot com Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: Irrelevant OS: Win XP Pro
Private report: No CVE-ID: None
 [2014-03-09 06:14 UTC] jake_hotson at hotmail dot com
Description:
------------
PHP ver 5.4.8.  Unable to test in 5.5.10 as seems incompatible with Apache 2.4.7.

Script below says that orange is an apple, but if the first foreach is commented out it correctly says that it is fruity.

Test script:
---------------
        $fruits = array(
          'apple' => 'fruity',
          'orange' => 'fruity',
        );
        foreach ($fruits as &$fruit) {
        }
        foreach ($fruits as $fruit => $description) {
          echo "$fruit is $description<br />\n";
        }


Expected result:
----------------
apple is fruity
orange is fruity

Actual result:
--------------
apple is fruity
orange is apple

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2014-03-09 06:48 UTC] requinix@php.net
-Status: Open +Status: Not a bug
 [2014-03-09 06:48 UTC] requinix@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

References. After the first loop $fruit is still a reference and that means attempting to change its value will affect whatever it was a reference to as well. In this situation you'll experience that as showing "<key> is <previous key>" in the last iteration.

unset($fruit) after the first loop.
 [2014-03-10 01:00 UTC] jake_hotson at hotmail dot com
Thanks.  Now found an almost-identical example as the first user-contributed item at http://www.php.net/manual/en/language.references.php (and upvoted it).

I blame my C/C++/Java background as the behaviour did seem so bizarre that it couldn't be by design (philosophically it wasn't, though logically it was).  Sorry for raising a non-bug.

Close.  Explanation accepted.
 
PHP Copyright © 2001-2026 The PHP Group
All rights reserved.
Last updated: Tue Oct 06 06:00:01 2026 UTC