Is the order of an associative array guaranteed in PHP?

前端 未结 4 398
一整个雨季
一整个雨季 2021-01-11 16:33

When I perform a foreach loop over an associatve array in php, the order in which it is performed is the order in which it is defined.

For example:

$         


        
相关标签:
4条回答
  • 2021-01-11 16:49

    This will never change.

    0 讨论(0)
  • 2021-01-11 17:00

    Because arrays are always ordered, and the easiest and fastest way to iterate the array is just going from the first element to the last one (so there is no good reason to change the behavior for foreach()), you can be reasonably sure that this behavior will not change.

    0 讨论(0)
  • 2021-01-11 17:10

    Your questions seems like you came from programming in Perl where "arrays" are not guaranteed to be in the order you created them. But in PHP it has always been ordered and will always be, otherwise a lot of code will break.

    0 讨论(0)
  • 2021-01-11 17:11

    From the PHP Manual

    An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more.

    and

    Arrays are ordered. The order can be changed using various sorting functions.

    So you can be certain (at least currently) that the order will be maintained. I would be very surprised if this behaviour were to change because it is clearly stated and because of this there will be a huge amount of code that relies on it.

    0 讨论(0)
提交回复
热议问题