gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 21:20:44 26 4
gpt4 key购买 nike

所以我已经经历了很多时间,但我从来没有能够真正理解它。它直接取自 php.net 文档,关于 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)...我只是不明白。感谢您的帮助。

最佳答案

关注我:

<?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]是引用。//一个$value的引用和最后一个数组元素即使在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 现在是 array(2, 4, 6, 6)

关于php - 有人可以向我解释这种行为(PHP,foreach),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50171319/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com