一个阵列上的空foreach改变了另一个阵列

时间:2014-02-21 18:22:33

标签: php arrays foreach

我有$array1。然后我按$array2 array_filter $array1创建$array2。当我只是迭代<? $array2 = array_filter($array1, function ($elem) use ($idsToExclude) { return in_array($elem["id"], $idsToExclude); }); ?> <? echo "== before iterating ==<br>"; print_r($array1); ?> <? foreach ($array2 as $elem) :?> <!-- WRYYYYYYY! --> <? endforeach;?> <? echo "== after iterating ==<br>"; print_r($array1); ?> (空循环)时,会以某种方式创建元素副本并替换现有元素。

以下是样本:

== before ==
17 =>     Array (
    id => 1
    name => Test account 1
)
18 =>     Array (
    id => 102
    name => Test account 2
)
19 =>     Array (
    id => 37
    name => Test account 3
)
20 =>     Array (
    id => 82
    name => Test account 4
)
21 =>     Array (
    id => 97
    name => Test account 5
)

== after ==
17 =>     Array (
    id => 1
    name => Test account 1
)
18 =>     Array (
    id => 97
    name => Test account 5
)
19 =>     Array (
    id => 37
    name => Test account 3
)
20 =>     Array (
    id => 82
    name => Test account 4
)
21 =>     Array (
    id => 97
    name => Test account 5
)

输出:

Test account 5

请注意,在第二个输出中Test account 2替换了foreach。如果$array1被评论,则{{1}}不会被更改。

1 个答案:

答案 0 :(得分:0)

$array1由以下代码创建:

foreach ($array1 as &$elem) {
    // Do something
}

注意&运算符允许更改循环中的原始$elem(而不是其副本)。因为&$elem没有取消设置after循环,所以程序遭受了未定义的行为。

所以正确的代码将是

foreach ($array1 as &$elem) {
    // Do something
}

unset($elem);