Bug #64018 [Opn->Nab]: missing elements from the result set when using foreach with referencing $value
Edit report at https://bugs.php.net/bug.php?id=64018&edit=1
ID: 64018
Updated by: cataphract@php.net
Reported by: potyo dot ada at gmail dot com
Summary: missing elements from the result set when using
foreach with referencing $value
-Status: Open
+Status: Not a bug
Type: Bug
Package: Scripting Engine problem
Operating System: Ubuntu 12.10
PHP Version: Irrelevant
Block user comment: N
Private report: N
New Comment:
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.
Previous Comments:
------------------------------------------------------------------------
[2013-01-18 11:41:39] potyo dot ada at gmail dot com
Tested using 5.3.5 and 5.4.10 versions
------------------------------------------------------------------------
[2013-01-18 11:40:40] 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
)
)
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=64018&edit=1
Thread (3 messages)