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

标签 php arrays loops foreach while-loop

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

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/

相关文章:

php - 使用ajax从html表单更新数据库

ruby - Ruby 变量前的感叹号

javascript - 如何在数据数组和对象的合并中使用对象分配而不是扩展语法?

r - 双重麻烦: number of items to replace is not a multiple of replacement length and sharing large matrices

Javascript 循环中的回调函数

php - 如何处理基于 MVC 的网站中的状态消息?

php - propel 2,mysql - 反向没有错误,没有创建 schema.xml

java - 需要删除csv中的空列

在 R 中的 data.table 中用 0 替换所有 NA

javascript - 单击按钮显示不同的文本,重复第一个文本