Is the order of an associative array guaranteed in PHP?

前端 未结 4 407
一整个雨季
一整个雨季 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 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.

提交回复
热议问题