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

PhpForeach

Php 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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohnView Question on Stackoverflow
Solution 1 - PhpPoonam BhattView Answer on Stackoverflow
Solution 2 - PhpHibou57View Answer on Stackoverflow
Solution 3 - PhpfastcodejavaView Answer on Stackoverflow
Solution 4 - PhpFentonView Answer on Stackoverflow