foreach in php5
So... many new things appear in PHP5... one of which is a significant change in the behavior of the foreach function. Take the following example:
in PHP4 this would have printed
This now works correctly thanks to the lovely &!
$array = array(array("asdf"=>456));
foreach ($array as $item) {
$item["asdf"] = 123;
}
print_r($array);
in PHP4 this would have printed
array (however in PHP 5, it prints
array ( asdf => 123 )
)
I hear you asking why! How is it that this function does not assign the value 123 to the "asdf" property any more? Well... my friends... here is the trap for the unwary. As of PHP5, the foreach function creates a copy of the items, whereas previously we operated directly on the items. So now, we need to have the following code to specify a reference assignment:
array (
array ( asdf => 456 )
)
$array = array(array("asdf"=>456));
foreach ($array as &$item) {
$item["asdf"] = 123;
}
print_r($array);
This now works correctly thanks to the lovely &!

