foreach 是否保证在 php 中按数组顺序迭代?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4733188/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 14:11:20  来源:igfitidea点击:

Is foreach guaranteed to iterate in the array order in php?

phpforeach

提问by John

When an array is passed to foreachis the output order guaranteed to be the same as the input? I know in some languages that the output order is not guaranteed since each element is processed at the same time.

传递数组时是否foreach保证输出顺序与输入相同?我知道在某些语言中无法保证输出顺序,因为每个元素都是同时处理的。

For example, I'm passing a sorted array to foreachto write to a file. I want to be sure that the array will be sorted in the output file.

例如,我将一个排序数组传递foreach给写入文件。我想确保数组将在输出文件中排序。

采纳答案by Poonam Bhatt

Yes ...whatever order you will give to foreach it will iterate in same orders. And in your case array will be sorted in the output file.

是的......无论你给 foreach 什么顺序,它都会以相同的顺序迭代。在你的情况下array will be sorted in the output file.

回答by Hibou57

The relevant reference might not be that of foreachor sorting as previously mentionned, but that of array instead.

相关的引用可能不是foreach前面提到的of或排序,而是数组的引用。

Language reference?—?Arrayssays:

语言参考?—?Arrays说:

An array in PHP is actually an ordered map.

PHP 中的数组实际上是一个有序映射。

回答by fastcodejava

This is correct, foreachwill output in same order as the input array .

这是正确的,foreach将按照与输入数组相同的顺序输出。

回答by Fenton

Yes - the items will be output in the same order they are in within the array.

是 - 项目将按照它们在数组中的相同顺序输出。