Are PHP Associative Arrays Ordered?

I come from the background of python, and the python data type, which is similar (dictionary), is a collection of unordered key value pairs.

I am wondering if the set of associative arrays of PHP is disordered? It seems that they are ordered.

$test = array( 'test' => 'test', 'bar' => 'bar', ); var_dump($test); var_dump(array_slice($test, 0, 1)); 

The test always comes in front of the bar, and I can slice this array, as you see. So is it always guaranteed that you order through php versions? Is the order only the order with which I declared the array? So, does something internally indicate a β€œtest” to place [0] in the array? I read http://php.net/manual/en/language.types.array.php , but it does not shed too much light on this problem. I appreciate your answers. Ty

+48
dictionary arrays php
Jun 06 2018-12-06T00:
source share
3 answers

PHP associative arrays are ordered (as well as numeric arrays), and PHP provides various functions for handling the order of the array keys, for example ksort() , uksort() and krsort()

In addition, 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 ​​with keys. This type is optimized for several different applications; it can be considered as an array, list (vector), hash table (map implementation), dictionary, collection, stack, queue, and possibly more. Other arrays can be used as array values, trees and multidimensional arrays are also possible.

+46
Jun 06 2018-12-06T00:
source share

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.

+7
Jun 06 2018-12-06T00:
source share

From php manual :

arrays are ordered. The order can be changed using various sorting functions. See the section on array functions for more details.

I relied on the fact that they were streamlined, and he worked consistently in every project that I had.

+1
Jun 06 2018-12-06T00:
source share



All Articles