Are PHP Associative Arrays ordered?

Solution 1:

PHP associative arrays (as well as numeric arrays) are ordered, and PHP supplies various functions to deal with the array key ordering like ksort(), uksort(), and krsort()

Further, PHP allows you to declare arrays with numeric keys out of order:

$a = array(3 => 'three', 1 => 'one', 2 => 'two');
print_r($a);

Array
(
    [3] => three
    [1] => one
    [2] => two
)
// Sort into numeric order
ksort($a);
print_r($a);
Array
(
    [1] => one
    [2] => two
    [3] => three
)

From the documentation:

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. As array values can be other arrays, trees and multidimensional arrays are also possible.

Solution 2:

The documentation states:

An array in PHP is actually an ordered map.

So yes, they are always ordered. Arrays are implemented as a hash table.

Solution 3:

The array is ordered but that does not mean the keys are sorted, it means that they are in a given order. Where the precise order is not specified, but it appears to be the order in which you introduced the key-value pairs in it.

To understand it, think what would it mean to not be ordered? Well think to a relation in a relational database. A relation is not intrinsically ordered: when you access it with a query the database, unless you provide an order clause, can return the same data in any order. Even if the data was not modified the same data can be returned in different order.

Solution 4:

From the php manual:

Arrays are ordered. The order can be changed using various sorting functions. See the array functions section for more information.

I have relied on the fact that they are ordered and it has worked consistently in every project I've had.