gpt4 book ai didi

php - foreach 是否在输入数组的副本上工作?

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

我一直在研究一些试题。关于数组迭代的问题之一。在这里:

What is the best way to iterate through the $myarray array, assuming you want to modify the value of each element as you do?

<?php
$myarray = array ("My String",
"Another String",
"Hi, Mom!");
?>

A. Using a for loop

B. Using a foreach loop

C. Using a while loop

D. Using a do…while loop

E. There is no way to accomplish this goals

我的回答是“当然是 foreach 循环”。但是根据答卷:

Normally, the foreach statement is the most appropriate construct for iterating through an array. However, because we are being asked to modify each element in the array, this option is not available, since foreach works on a copy of the array and would therefore result in added overhead. Although a while loop or a do…while loop might work, because the array is sequentially indexed a for statement is best suited for the task, making Answer A correct.

我仍然认为 foreach 是最好的。只要我将它与键一起使用,我就可以修改值。

<?php
foreach($myarray as $k=>$v){
$myarray[$k] = "Modified ".$v;
}
?>

我错过了什么吗?

最佳答案

according to the answer sheet:

this option is not available, since foreach works on a copy of the array and would therefore result in added overhead

废话。

如果需要证明,可以引用取值:

<?php
foreach($myarray as &$v){
$v = "Modified ".$v;
}
?>

I still think foreach is the best. And as long as i use it with key i can modify values.

我同意。

Do I miss something?

没有。

关于php - foreach 是否在输入数组的副本上工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8079563/

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