douzi8112 2017-06-18 01:34
浏览 69

在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?

  • 写回答

2条回答 默认 最新

  • douyu8187 2017-06-18 01:37
    关注

    $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);
    
    评论

报告相同问题?