PHP Reference ยท Array Functions
PHP ksort() and krsort() functions
Reference for PHP ksort() and krsort(): sort an array by its keys, ascending or descending, with sort flags, mixed key types and stable ordering explained.
ksort() sorts an array by its keys from low to high, and krsort() sorts from high to low. Every value stays with its key; only the order of the entries changes. Both functions work in place and return true.
Typical uses are printing a map in alphabetical order, sorting a sparse numeric array by index, or producing stable output (for example before hashing or comparing configuration arrays).
<?php $a = ["b" => 1, "c" => 2, "a" => 3]; ksort($a); // a, b, c krsort($a); // c, b, a
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
ksort(array &$array, int $flags = SORT_REGULAR): true krsort(array &$array, int $flags = SORT_REGULAR): true
| Name | Description |
|---|---|
$array |
The array to sort, passed by reference. |
$flags |
Comparison mode: SORT_REGULAR (default), SORT_NUMERIC, SORT_STRING, SORT_NATURAL or SORT_LOCALE_STRING, optionally combined with SORT_FLAG_CASE. |
Return value: always true in PHP 8.2 and later (earlier versions declared bool).
Usage notes
- Keys are the sort criterion; values are ignored. To sort by value and keep keys, use
asort()orarsort(). - In place. The return value is only
true; copy the array first if you need the original order. - Integer and string keys can be mixed. In
SORT_REGULARmode PHP 8 compares an integer with a non-numeric string by comparing the number as a string, so the result can look odd. UseSORT_STRINGorSORT_NUMERICwhen the key types are mixed. - Case matters. By default uppercase letters sort before lowercase ones. Add
SORT_FLAG_CASE | SORT_STRINGfor case-insensitive order. - Natural order (
img2beforeimg10):SORT_NATURAL. - Stable since PHP 8.0, though keys are unique, so stability rarely matters here.
- Custom order of keys needs
uksort(). - Predictable output: sorting keys before
json_encode()orvar_export()makes the text identical for equal data.