Strange foreach loop behaviour in PHP

时间:2016-05-13 12:47:21

标签: php for-loop foreach

Can somebody explain why the second foreach loop outputs the item with ID = 2 twice?

The '&' in the first loop is intended to alter the real object and not a copy. When I change field name $value in second loop to something else, it works as expected but I would like to understand, why it comes to this output.

$a = array("ID" => "1");
$b = array("ID" => "2");
$d = array("ID" => "3");
$c = array($a, $b, $d);

foreach ($c as &$value)
{
    $value['foo'] = rand(0, 10000);
}

print_r($c);

foreach ($c as $value)
{
    print_r($value);
}

output:

Array
(
    [0] => Array
        (
            [ID] => 1
            [foo] => 5673
        )

    [1] => Array
        (
            [ID] => 2
            [foo] => 5421
        )

    [2] => Array
        (
            [ID] => 3
            [foo] => 149
        )

)
Array
(
    [ID] => 1
    [foo] => 5673
)
Array
(
    [ID] => 2
    [foo] => 5421
)
Array
(
    [ID] => 2
    [foo] => 5421
)

1 个答案:

答案 0 :(得分:-1)

来自其中一个SO answer

这是一个记录良好的PHP行为 请参阅php.net的foreach页面上的warning

  

警告

     

$ value 的引用,即使在 foreach 循环之后,最后一个数组元素仍然存在。建议通过unset()来销毁它。

所以你的代码应该是:

<?php
$a = array("ID" => "1");
$b = array("ID" => "2");
$d = array("ID" => "3");
$c = array($a, $b, $d);

foreach ($c as &$value)
{
    $value['foo'] = rand(0, 10000);
}

print_r($c);

unset($value);

foreach ($c as $value)
{
    print_r($value);
}

输出:

Array
(
    [0] => Array
        (
            [ID] => 1
            [foo] => 6465
        )

    [1] => Array
        (
            [ID] => 2
            [foo] => 4562
        )

    [2] => Array
        (
            [ID] => 3
            [foo] => 2629
        )

)
Array
(
    [ID] => 1
    [foo] => 6465
)
Array
(
    [ID] => 2
    [foo] => 4562
)
Array
(
    [ID] => 3
    [foo] => 2629
)