I was playing with PHP recently and wanted to assign variable in foreach loop and pass value by reference at the same time. I was a little bit surprised that didn't work. Code:
$arr = array(
'one' => 'xxxxxxxx',
'two' => 'zzzzzzzz'
);
foreach ($foo = $arr as &$value) {
$value = 'test';
}
var_dump($foo);
Result:
array(2) { ["one"]=> string(8) "xxxxxxxx" ["two"]=> string(8) "zzzzzzzz" }
The following approach obviously does work:
$arr = array(
'one' => 'xxxxxxxx',
'two' => 'zzzzzzzz'
);
$foo = $arr;
foreach ($foo as &$value) {
$value = 'test';
}
var_dump($foo);
Result:
array(2) { ["one"]=> string(4) "test" ["two"]=> &string(4) "test" }
Does someone know why those snippets are not equivalent and what is being done behind the scenes?