Wednesday, April 18, 2012

Weird PHP behaviour - What's going on?

Just came across this bug recently in a PHP app. Not sure what's going on.



Basically, it shows up when using a combination of two foreach (one with &, one without).



Here's a test code that reproduce the problem:



$items = array(

array('id'=>1, 'name'=>'foo', 'value'=>150),

array('id'=>2, 'name'=>'bar', 'value'=>190)
);


foreach($items as &$item)
{

$item['percentage'] = $item['value'] * 0.75;

}

var_dump($items); // All Good

foreach($items as $item)
{

var_dump($item); // Shows 1st item twice
}


The second foreach loop runs the block twice, as expected, but $item remains stuck on the first item.



I understand this is likely caused by the use of the reference & in the first loop but I don't see why it should behave like this..



Any idea? is that a bug?



Getting the same result on 5.3.8, 5.3.10 & 5.4





No comments:

Post a Comment