gpt4 book ai didi

php - while(list($key, $value) = each($array)) vs. foreach($array as $key => $value)?

转载 作者:IT王子 更新时间:2023-10-29 01:01:57 26 4
gpt4 key购买 nike

最近我遇到了这个奇怪的问题:

while(list($key, $value) = each($array))

没有列出所有数组值,将其替换为...

foreach($array as $key => $value)

...完美运行。

而且,我现在很好奇..这两者之间有什么区别?

最佳答案

你之前是否遍历过这个数组? each() 会记住它在数组中的位置,因此如果您不reset() 它,您可能会遗漏项目。

reset($array);
while(list($key, $value) = each($array))

就其值(value)而言,这种遍历数组的方法很古老,已被更为惯用的 foreach 所取代。我不会使用它,除非你特别想利用它一次一个项目的特性。

array each ( array &$array )

Return the current key and value pair from an array and advance the array cursor.

After each() has executed, the array cursor will be left on the next element of the array, or past the last element if it hits the end of the array. You have to use reset() if you want to traverse the array again using each.

(来源:PHP Manual)

关于php - while(list($key, $value) = each($array)) vs. foreach($array as $key => $value)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3304885/

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