Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the order of an associative array guaranteed in PHP?

Tags:

php

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:

$arr = array("z" => "z", "a" => "a", "b" => "b");

foreach($arr as $key => val)
  print("$key: $val\n");

Outputs:

z: z
a: a
b: b

Whereas

$arr = array("a" => "a", "b" => "b", "z" => "z");

Outputs:

a: a
b: b
z: z

So my question is then: is this behavior defined at a specification level? Can I have reasonable certainty that this behavior will not be changed in future versions of PHP?

like image 926
Asuah Avatar asked Jun 04 '09 14:06

Asuah


People also ask

Are PHP associative arrays ordered?

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

Does PHP preserve array order?

PHP array is an ordered map, so, it's a map that keeps the order. array elements just keep the order since they were added that's all.

Can associative arrays sort?

The arsort() function sorts an associative array in descending order, according to the value. Tip: Use the asort() function to sort an associative array in ascending order, according to the value. Tip: Use the krsort() function to sort an associative array in descending order, according to the key.

What are the advantages of associative arrays in PHP?

Advantages of Associative ArrayWe can save more data, as we can have a string as key to the array element, where we can have associated data to the value to be stored, like in our example, we stored the type of the car as key along with the name of the car as value.


1 Answers

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.

like image 123
Tom Haigh Avatar answered Nov 11 '22 13:11

Tom Haigh