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.

ksort and srsort functions

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

These functions returns TRUE on success or FALSE on failure. These functions useful mainly for associative arrays and accept two parameters:

  1. array as input

  2. sort_flags (optional) modify the behavior of the sort. Sorting type flags:

    SORT_REGULAR: compare items normally (don't change types)

    SORT_NUMERIC: compare items numerically

    SORT_STRING: compare items as strings

    SORT_LOCALE_STRING: compare items as strings, based on the current locale.

    SORT_NATURAL: compare items as strings using "natural ordering" like natsort()

    SORT_FLAG_CASE: can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort strings case-insensitively

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.

ksort and krsort examples

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

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.

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