Is foreach guaranteed to iterate in the array order in php?
PhpForeachPhp Problem Overview
When an array is passed to foreach
is 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.
For example, I'm passing a sorted array to foreach
to write to a file. I want to be sure that the array will be sorted in the output file.
Php Solutions
Solution 1 - Php
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.
Solution 2 - Php
The relevant reference might not be that of foreach
or sorting as previously mentionned, but that of array instead.
Language reference — Arrays says: > An array in PHP is actually an ordered map.
Solution 3 - Php
This is correct, foreach
will output in same order as the input array .
Solution 4 - Php
Yes - the items will be output in the same order they are in within the array.