Are PHP Associative Arrays ordered?

前端 未结 4 1551
走了就别回头了
走了就别回头了 2020-11-30 11:52

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

相关标签:
4条回答
  • 2020-11-30 12:32

    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.

    0 讨论(0)
  • 2020-11-30 12:40

    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.

    0 讨论(0)
  • 2020-11-30 12:43

    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.

    0 讨论(0)
  • 2020-11-30 12:54

    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 wich 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.

    0 讨论(0)
提交回复
热议问题