在foreach循环中设置变量并通过引用传递

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?

$foo = $arr is trans by value, not reference, you should use $foo = &$arr. You can refer to Are arrays in PHP passed by value or by reference?

try this, live demo.

$arr = array(
    'one' => 'xxxxxxxx',
    'two' => 'zzzzzzzz'
);

foreach ($foo = &$arr as &$value) {
    $value = 'test';
}

var_dump($foo);
foreach ($foo = $arr as &$value) {
    $value = 'test';
}

first you assign the value of $arr[0] to $foo[0] then take that value and make that value = 'test' (this will not change $arr or $foo values "useless statement")

But here

$foo = $arr;
foreach ($foo as &$value) {
    $value = 'test';
}

first you asign $arr to $foo then go to for each statement , get the values of $foo and modify it ex: $foo[0]='test' , $foo[1]='test' ...