0
0
PhpHow-ToBeginner · 3 min read

How to Use ksort and krsort in PHP: Sorting Arrays by Keys

In PHP, use ksort() to sort an array by its keys in ascending order, and krsort() to sort by keys in descending order. Both functions sort the original array and return true on success.
📐

Syntax

ksort(array &$array, int $sort_flags = SORT_REGULAR): bool sorts the array by keys in ascending order.

krsort(array &$array, int $sort_flags = SORT_REGULAR): bool sorts the array by keys in descending order.

The $array is passed by reference and is modified directly. The optional $sort_flags controls sorting behavior (e.g., numeric, string).

php
ksort(array &$array, int $sort_flags = SORT_REGULAR): bool
krsort(array &$array, int $sort_flags = SORT_REGULAR): bool
💻

Example

This example shows how to sort an associative array by keys in ascending order using ksort() and in descending order using krsort().

php
<?php
$fruits = [
    "d" => "Date",
    "b" => "Banana",
    "a" => "Apple",
    "c" => "Cherry"
];

// Sort by keys ascending
ksort($fruits);
echo "Sorted by keys ascending:\n";
print_r($fruits);

// Sort by keys descending
krsort($fruits);
echo "\nSorted by keys descending:\n";
print_r($fruits);
?>
Output
Sorted by keys ascending: Array ( [a] => Apple [b] => Banana [c] => Cherry [d] => Date ) Sorted by keys descending: Array ( [d] => Date [c] => Cherry [b] => Banana [a] => Apple )
⚠️

Common Pitfalls

  • Both ksort() and krsort() modify the original array; they do not return a new sorted array.
  • Passing a non-array or a non-associative array may not produce meaningful results.
  • Using the wrong sort flag can lead to unexpected order, so choose SORT_REGULAR, SORT_NUMERIC, or SORT_STRING carefully.
php
<?php
// Wrong: expecting a new sorted array
$original = ['b' => 2, 'a' => 1];
$sorted = ksort($original); // $sorted is true, not sorted array

// Right: ksort sorts in place
ksort($original);
print_r($original);
?>
Output
Array ( [a] => 1 [b] => 2 )
📊

Quick Reference

FunctionDescriptionSort OrderReturns
ksortSorts array by keysAscendingtrue on success
krsortSorts array by keysDescendingtrue on success

Key Takeaways

Use ksort() to sort arrays by keys in ascending order.
Use krsort() to sort arrays by keys in descending order.
Both functions sort the original array in place and return true on success.
Choose the correct sort flag to control sorting behavior if needed.
Do not expect these functions to return a new sorted array; they modify the input array.