[Previous] [Contents] [Next]

Sorting associative arrays

It's often desirable to keep the key/value associations when sorting associative arrays. To maintain the key/value association the asort( ) and arsort( ) functions are used:

asort(array subject [, integer sort_flag])
arsort(array subject [, integer sort_flag])

Like sort( ) and rsort( ), these functions rearrange the elements in the subject array from lowest to highest and highest to lowest, respectively. The following example shows a simple array sorted by asort( ):

$map =
  array("o"=>"kk", "e"=>"zz", "z"=>"hh", "a"=>"rr");
asort($map);
print_r($map);

The print_r( ) function outputs the structure of the sorted array:

Array ( [z] => hh
        [o] => kk
        [a] => rr
        [e] => zz )

When assort( ) and arsort( ) are used on nonassociative arrays, the order of the elements is arranged in sorted order, but the indexes that access the elements don't change. This might seem a bit weird; effectively the indexes are treated as association keys in the resulting array. The following example shows what is happening:

$numbers = array(24, 19, 3, 16, 56, 8, 171);
asort($numbers);
print_r($numbers);

This outputs:

Array ( [2] => 3
        [5] => 8
        [3] => 16
        [1] => 19
        [0] => 24
        [4] => 56
        [6] => 171 )

[Previous] [Contents] [Next]