Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

foreach

php

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.

like image 967
John Avatar asked Jan 19 '11 08:01

John


People also ask

Does foreach work on arrays?

The forEach method is also used to loop through arrays, but it uses a function differently than the classic "for loop". The forEach method passes a callback function for each element of an array together with the following parameters: Current Value (required) - The value of the current array element.

Does foreach mutate array?

forEach() does not mutate the array on which it is called.


1 Answers

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.

like image 196
Poonam Bhatt Avatar answered Sep 20 '22 20:09

Poonam Bhatt