php while(list($key, $value) = each($array)) vs. foreach($array as $key => $value)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3304885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
while(list($key, $value) = each($array)) vs. foreach($array as $key => $value)?
提问by jolt
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)
...worked perfectly.
......完美地工作。
And, I'm curious now.. what is the difference between those two?
而且,我现在很好奇……这两者有什么区别?
回答by John Kugelman
Had you previously traversed the array? each()remembers its position in the array, so if you don't reset()it you can miss items.
您之前是否遍历过数组?each()记住它在数组中的位置,所以如果你不这样做reset(),你可能会错过项目。
reset($array);
while(list($key, $value) = each($array))
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.
值得一提的是,这种数组遍历方法很古老,已被更惯用的 foreach 所取代。我不会使用它,除非你特别想利用它一次一件物品的特性。
arrayeach( 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 usereset()if you want to traverse the array again usingeach.
每个数组(数组&$array )
从数组中返回当前的键值对并前进数组光标。
后
each()已执行,数组指针将被留在数组的下一个元素,或过去的最后一个元素,如果它击中了数组的结尾。你必须使用reset(),如果你想再次遍历数组使用each。
(Source: PHP Manual)
(来源:PHP 手册)
回答by ircmaxell
Well, one difference is that each()will only work on arrays (well only work right). foreachwill work on any object that implements the traversableinterface (Which of course includes the built in array type).
嗯,一个区别是它each()只能在数组上工作(只能正常工作)。 foreach将适用于实现该traversable接口的任何对象(当然包括内置数组类型)。
There may be a micro-optimization in the foreach. Basically, foreach is equivilant to the following:
foreach 中可能有微优化。基本上,foreach 等同于以下内容:
$array->rewind();
while ($array->valid()) {
$key = $array->key();
$value = $array->current();
// Do your code here
$array->next();
}
Whereas eachbasically does the following:
而each基本上执行以下操作:
$return = $array->valid() ? array($array->key(), $array->current()) : false;
$array->next();
return $return;
So three lines are the same for both. They are both very similar. There may be some micro-optimizations in that eachdoesn't need to worry about the traversableinterface... But that's going to be minor at best. But it's also going to be offset by doing the boolean cast and check in php code vs foreach's compiled C... Not to mention that in your while/eachcode, you're calling two language constructs and one function, whereas with foreachit's a single language construct...
所以三行是相同的。他们都非常相似。可能会有一些微优化,each不需要担心traversable界面......但这充其量只是次要的。但它也将通过执行布尔转换和检查 php 代码与foreach编译的 C来抵消......更不用说在你的while/each代码中,你调用了两种语言结构和一个函数,而foreach它是一种语言构造...
Not to mention that foreachis MUCH more readable IMHO... So easier to read, and more flexible means that -to me- foreachis the clear winner. (that's not to say that eachdoesn't have its uses, but personally I've never needed it)...
更不用说这foreach是更易读恕我直言......所以更容易阅读,更灵活意味着 - 对我foreach来说-是明显的赢家。(这并不是说它each没有用途,但我个人从未需要它)...
回答by Xeoncross
Warning!Foreach creates a copy of the arrayso you cannot modify it while foreach is iterating over it. each()still has a purpose and can be very useful if you are doing live edits to an array while looping over it's elements and indexes.
警告!Foreach 创建数组的副本,因此在 foreach 对其进行迭代时您无法修改它。each()如果您在循环遍历数组的元素和索引的同时对数组进行实时编辑,它仍然有一个目的并且非常有用。
// Foreach creates a copy
$array = [
"foo" => ['bar', 'baz'],
"bar" => ['foo'],
"baz" => ['bar'],
"batz" => ['end']
];
// while(list($i, $value) = each($array)) { // Try this next
foreach($array as $i => $value) {
print $i . "\n";
foreach($value as $index) {
unset($array[$index]);
}
}
print_r($array); // array('baz' => ['end'])
Both foreachand whilewill finish their loops and the array "$array" will be changed. However, the foreach loop didn't change while it was looping - so it still iterated over every element even though we had deleted them.
双方foreach并while会完成他们的循环和阵列“ $array”将被改变。然而,foreach 循环在循环时并没有改变——所以它仍然迭代每个元素,即使我们已经删除了它们。
Update: This answer is not a mistake.
更新:这个答案不是错误。
I thought this answer was pretty straight forward but it appears the majority of users here aren't able to appreciate the specific details I mention here.
我认为这个答案非常直接,但似乎这里的大多数用户无法理解我在这里提到的具体细节。
Developers that have built applications using libdom (like removing elements) or other intensive map/list/dict filtering can attest to the importance of what I said here.
使用 libdom(如删除元素)或其他密集的 map/list/dict 过滤构建应用程序的开发人员可以证明我在这里所说的重要性。
If you do not understand this answer it will bite you some day.
如果你不理解这个答案,它总有一天会咬你。
回答by Dan McGrath
If you passed eachan object to iterate over, the PHP manual warns that it may have unexpected results.
如果您传递each一个对象进行迭代,PHP 手册会警告它可能会产生意外结果。
What exactly is in $array
究竟是什么 $array

