while(list($key, $value) = each($array)) vs. foreach($array as $key => $value)? [英] while(list($key, $value) = each($array)) vs. foreach($array as $key => $value)?

查看:30
本文介绍了while(list($key, $value) = each($array)) vs. foreach($array as $key => $value)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Recently I experienced this weird problem:

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

没有列出所有数组值,用...替换它

was not listing all array values, where replacing it with...

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

...完美运行.

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

And, I'm curious now.. what is the difference between those two?

推荐答案

您之前是否遍历过数组?each() 记住它在数组中的位置,所以如果你不 reset() 它你可能会错过项目.

Had you previously traversed the array? each() remembers its position in the array, so if you don't reset() it you can miss items.

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

值得一提的是,这种数组遍历方法很古老,已被更惯用的 foreach 所取代.我不会使用它,除非您特别想利用它一次一件物品的特性.

For what it's worth this method of array traversal is ancient and has been superseded by the more idiomatic foreach. I wouldn't use it unless you specifically want to take advantage of its one-item-at-a-time nature.

array 每个 ( array &$array )

array each ( array &$array )

从数组中返回当前的键值对并前进数组光标.

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

each() 执行后,数组光标将停留在数组的下一个元素上,如果到达数组末尾,则超过最后一个元素.如果要使用 each 再次遍历数组,则必须使用 reset().

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 手册)

这篇关于while(list($key, $value) = each($array)) vs. foreach($array as $key => $value)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆