gpt4 book ai didi

php - 需要帮助来调试 PHP 代码

转载 作者:可可西里 更新时间:2023-11-01 00:39:20 24 4
gpt4 key购买 nike

我有如下代码,

 <?php
$a = [1,2,3];
foreach($a as &$val) {
$val = $val + 1;
}

foreach($a as $val) {
$val = $val - 1;
}

var_dump($a);

// output 2,3,1
?>

我得到输出 2,3,1 作为最终数组而不是 2,3,4,我不明白 php 如何解释这段代码,谁能帮我理解这里的情况?

最佳答案

您需要在第一个 foreach() 中对引用调用 unset() 以获得预期的行为:

$a = [1, 2, 3];

foreach($a as &$val)
{
$val = $val + 1;
}

unset($val);

// $a = [2, 3, 4];

请参阅 documentation 中的注释为此:

Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset().

关于php - 需要帮助来调试 PHP 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50309088/

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