php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #64018 missing elements from the result set when using foreach with referencing $value
Submitted: 2013-01-18 11:40 UTC Modified: 2013-01-18 12:15 UTC
From: potyo dot ada at gmail dot com Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: Irrelevant OS: Ubuntu 12.10
Private report: No CVE-ID: None
 [2013-01-18 11:40 UTC] potyo dot ada at gmail dot com
Description:
------------
If we try to change the array elements in one foreach loop using referenced 
$value, and in a second foreach loop remove some elements from the array, then 
the resulting array misses some element, some elements are duplicated, or simply 
nothing is removed, depending on that, which element we want to remove from the 
array in the second loop.

Test script:
---------------
$a=array(array('a'=>'11', 'aa'=>'22'), array('a'=>'33', 'aa'=>'44'), array('a'=>'55', 'aa'=>'66'));
foreach ($a as &$v) // if we use $k=>$v here
{
	$v['c']='99'; // and $a[$k]['c']='99' here, then it produces the expected result
}
foreach ($a as $k=>$v)
{
	if ($v['aa']=='22')
	{
		unset($a[$k]); // 
	}
}
print_r($a);


Expected result:
----------------
Array
(
    [1] => Array
        (
            [a] => 33
            [aa] => 44
            [c] => 99
        )

    [2] => Array
        (
            [a] => 33
            [aa] => 44
            [c] => 99
        )

)

Actual result:
--------------
Array
(
    [1] => Array
        (
            [a] => 33
            [aa] => 44
            [c] => 99
        )

    [2] => Array
        (
            [a] => 55
            [aa] => 66
            [c] => 99
        )

)


Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2013-01-18 11:41 UTC] potyo dot ada at gmail dot com
Tested using 5.3.5 and 5.4.10 versions
 [2013-01-18 12:15 UTC] cataphract@php.net
-Status: Open +Status: Not a bug
 [2013-01-18 12:15 UTC] cataphract@php.net
Not a bug; when the second loop starts $v is still a reference to the last $a element and you're writing to that reference.
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Fri Jul 18 16:00:02 2025 UTC