74

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.

6
  • 3
    (reference) php.net/manual/en/control-structures.foreach.php
    – Gordon
    Jan 19, 2011 at 8:41
  • Answers above, but have a look at array_multisort() in case you ever need to sort the array before doing a foreach loop: php.net/manual/en/function.array-multisort.php
    – o1iver
    Jan 19, 2011 at 14:32
  • 2
    I came here with the same question after reading php foreach doc. It doesn't explicity state that order will remain. I'm not talking about examples neither comments. The only reference is to reset() talking about the current element and the next element.
    – Sebastian
    Jun 4, 2013 at 19:22
  • 1
    And me neither. I've just looked at the so called “reference”, and could not see anything stating PHP preserves input order of associative arrays, per specification. Unless there is another more meaningful reference, the question is still unanswered (formally speaking), and it may as much be implementation or version dependant.
    – Hibou57
    Aug 12, 2013 at 8:07
  • I really wish you had given a code example in your question. Jun 25, 2016 at 6:10

4 Answers 4

57

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.

0
18

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.

8

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

2

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.