有人可以解释我这种行为(PHP,foreach)

时间:2018-05-04 09:12:12

标签: php

所以我经历了相当多的时间,但我从来没有真正理解它。它直接来自php.net doc,它关于foreach循环:

<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
    $value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
unset($value); // break the reference with the last element
?>

在某些时候,php.net说你必须小心,因为:

即使在foreach循环之后,$ value和最后一个数组元素的引用仍然存在。建议通过unset()销毁它。否则您将遇到以下行为:

<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
    $value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)

// without an unset($value), $value is still a reference to the last item: $arr[3]

foreach ($arr as $key => $value) {
    // $arr[3] will be updated with each value from $arr...
    echo "{$key} => {$value} ";
    print_r($arr);
}
// ...until ultimately the second-to-last value is copied onto the last value

// output:
// 0 => 2 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 2 )
// 1 => 4 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 4 )
// 2 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 )
// 3 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 )
?>

这到底是怎么回事?是否有一个逻辑背后(即使是错误的逻辑,因为它不是预期的行为)?但我真的不明白,有人能解释一下这是怎么回事?

对我来说应该是:

// output:
// 0 => 2 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 8 )
// 1 => 4 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 8 )
// 2 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 8 )
// 3 => 8 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 8 )

因为它表示最后一个数组元素保留(并且数组[3]的最后一个值为8)... 我只是不明白。谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

跟我来:

<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
    $value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)

// without an unset($value), $value is still a reference to the last item: $arr[3]

所以$ arr [3]是引用。对$值的引用和最后一个数组元素在foreach循环之后仍然存在

foreach ($arr as $key => $value) {
    // $arr[3] will be updated with each value from $arr...
    echo "{$key} => {$value} ";
    print_r($arr);
}
// ...until ultimately the second-to-last value is copied onto the last value

// output:
// 0 => 2 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 2 )
// 1 => 4 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 4 )
// 2 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 )
// 3 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 )
?>

$ arr [3]和$ value指向同一个地方。

when $key = 0, $value =2 => $value = $arr[3]=2
when $key = 1, $value =4 => $value = $arr[3]=4
when $key = 2, $value =6 => $value = $arr[3]=6

这次,$ arr现在是数组(2,4,6,6)