php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #54189 foreach changes array values after iterating by reference followed by foreach
Submitted: 2011-03-08 08:11 UTC Modified: 2011-03-08 09:24 UTC
Votes:1
Avg. Score:5.0 ± 0.0
Reproduced:0 of 0 (0.0%)
From: phazei at gmail dot com Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 5.2.17 OS: RHEL 5.6
Private report: No CVE-ID: None
 [2011-03-08 08:11 UTC] phazei at gmail dot com
Description:
------------
(I searched through the bug reports and found some foreach pointer issues, but 
none related to this)

If I simply go through an array with a referenced value like so:
foreach ($array as &$value) {  }

And then go through it again, not referenced, like so:
foreach ($array as $value) {  }

Both times using the same variable $value, then during the second foreach, the 
second to the last value is actually copied over the last value changing the 
array.

If I simply use $value2 there is no issue.

Test script:
---------------
$array = array('aaaaa','bbbbb','ccccc','ddddd','eeeee');
echo '1) '.print_r($array, true).'<br>';
foreach ($array as &$value) {  }
echo '2) '.print_r($array, true).'<br> 3) ';
foreach ($array as $key => $value) { echo "[$key] => $value "; }
echo '<br> 4) '.print_r($array, true).'<br>';

Expected result:
----------------
1) Array ( [0] => aaaaa [1] => bbbbb [2] => ccccc [3] => ddddd [4] => eeeee ) 
2) Array ( [0] => aaaaa [1] => bbbbb [2] => ccccc [3] => ddddd [4] => eeeee ) 
3) [0] => aaaaa [1] => bbbbb [2] => ccccc [3] => ddddd [4] => eeeee 
4) Array ( [0] => aaaaa [1] => bbbbb [2] => ccccc [3] => ddddd [4] => eeeee ) 

Actual result:
--------------
1) Array ( [0] => aaaaa [1] => bbbbb [2] => ccccc [3] => ddddd [4] => eeeee ) 
2) Array ( [0] => aaaaa [1] => bbbbb [2] => ccccc [3] => ddddd [4] => eeeee ) 
3) [0] => aaaaa [1] => bbbbb [2] => ccccc [3] => ddddd [4] => ddddd 
4) Array ( [0] => aaaaa [1] => bbbbb [2] => ccccc [3] => ddddd [4] => ddddd ) 

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2011-03-08 09:24 UTC] scottmac@php.net
-Status: Open +Status: Bogus
 [2011-03-08 09:24 UTC] scottmac@php.net
This is on the foreach manual page.

Between the two foreach loops, $value is a reference to the last entry in the 
array.

When the second loop starts you then start assigning new values to $value which 
reference the last element of the array.
 [2015-01-01 20:29 UTC] chealer at gmail dot com
The problematic behavior behind this issue is being tracked in #62132.
 
PHP Copyright © 2001-2019 The PHP Group
All rights reserved.
Last updated: Fri Dec 13 10:01:24 2019 UTC