[Previous] [Contents] [Next]


Sorting on keys

Rather than sort on element values, the ksort( ) and krsort( ) functions rearrange elements in an array by sorting on the keys or the indexes:

integer ksort(array subject [, integer sort_flag])
integer krsort(array subject [, integer sort_flag])

ksort( ) sorts the elements in the subject array from lowest key to highest key, and krsort( ) sorts in the reverse order. The following example demonstrates the ksort( ) function:

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

ksort($map);
print_r($map);

The sorted array $map is now:

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

There is little point in using ksort( ) on an integer-indexed array because the keys are already in order. When krsort( ) is used on an indexed array, it reverses the order of the elements.


[Previous] [Contents] [Next]