Are PHP Associative Arrays ordered?

05/05/2020 16:30:02

I come from python background and the python datatype which is similar (a dictionary) is an unordered set of key value pairs.

I am wondering if PHP associative arrays are unordered? They appear to be ordered.

$test = array(
  'test' => 'test',
  'bar' => 'bar',
);

var_dump($test);    

var_dump(array_slice($test, 0, 1));

Test always comes before bar and I can slice this array as you see. So is this always guaranteed to be ordered across php versions? Is the order just the order that I have declared the array with? So something is internally pointing 'test' to place [0] in the array? I have read http://php.net/manual/en/language.types.array.php but it doesn't shed too much light on this issue. I appreciate your responses. Ty

Verified Answer (61 Votes)

06/06/2012 18:02:07

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.

61

Answer #2 (9 Votes)

06/06/2012 18:02:58

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.

9

Answer #3 (2 Votes)

06/06/2012 18:03:31

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.

2
3
Hack Hex uses Stack Exchance API by the Stack Exchange Inc. to scrape questions/answers under Creative Commons license.