I've encountered some strange behavior of PHP's foreach loop, which I can't explain. Maybe you can help me.
Here's a simple test script:
function mod(&$item){
$item["position"] = preg_replace("/[^0-9]+/","",$item["position"]);
$item["count"] = 2*$item["count"];
}
$items = [
["position" => "1", "count" => 4],
["position" => "2", "count" => 3],
];
echo "before: <br>";
foreach($items as $item){
echo var_dump($item) . "<br>";
}
echo "modifying items...<br>";
foreach($items as &$item){
mod($item);
}
echo "after: <br>";
foreach($items as $item){
echo var_dump($item) . "<br>";
}
?>
The output of the script is the following:
before:
array(2) { ["position"]=> string(1) "1" ["count"]=> int(4) }
array(2) { ["position"]=> string(1) "2" ["count"]=> int(3) }
modifying items...
after:
array(2) { ["position"]=> string(1) "1" ["count"]=> int(8) }
array(2) { ["position"]=> string(1) "1" ["count"]=> int(8) }
It seems as if the for loop has looped over item[0] twice but has left out item[1], which is very confusing. Can someone explain this behavior to me?
Thank you very much!