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?
So yes, they are always ordered. Arrays are implemented as a hash table.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With