Please consider this test:
$data=[["id"=>1,"text"=>"One"],["id"=>2,"text"=>"Two"]];
foreach((array)$data as &$iter)
$iter["append"]=true;
print_r($data);
This is the output
Array
(
[0] => Array
(
[id] => 1
[text] => One
)
[1] => Array
(
[id] => 2
[text] => Two
)
)
I want to iter over an array and add another key inside the associative array, this is why $iter is passed by ref. I set the cast inside the "foreach" to be sure that an empty/null variable can be accepted without errors by foreach statement.
As you see in the output the foreach doesn't append the value, but if I remove the cast it works.
foreach($data as &$iter)
$iter["append"]=true;
print_r($data);
This is the (right) output
Array
(
[0] => Array
(
[id] => 1
[text] => One
[append] => 1
)
[1] => Array
(
[id] => 2
[text] => Two
[append] => 1
)
)
I solved casting with a separate command outside the foreach, but my question is:
Is this a bug?
This test was run on PHP Version 5.6.14 (apache-2.4 windows-10)
$variable = (array) $variable;.$variable = new StdClass;And your first code block works, would mean you have done an assignment implicit in the foreach header, which is not going to work, since after that you would have an array.