PHP ksort Function
last modified March 13, 2025
The PHP ksort
function sorts an array by key in ascending order.
It maintains key-value associations, making it ideal for associative arrays.
Basic Definition
The ksort
function sorts an array by its keys while preserving
the relationship between keys and values. It modifies the original array.
Syntax: ksort(array &$array, int $flags = SORT_REGULAR): bool
.
The optional flags parameter controls sorting behavior. Returns true on success.
Basic ksort Example
This demonstrates sorting a simple associative array by its keys in ascending order.
<?php $fruits = [ "d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple" ]; ksort($fruits); foreach ($fruits as $key => $val) { echo "$key = $val\n"; }
Output will show keys in alphabetical order: a, b, c, d. The original array is modified, with key-value pairs maintained during sorting.
Sorting Numeric Keys
ksort
works with numeric keys, sorting them in ascending order.
<?php $numbers = [ 10 => "ten", 2 => "two", 5 => "five", 1 => "one" ]; ksort($numbers); print_r($numbers);
The output will show keys in order: 1, 2, 5, 10. Note that numeric keys are sorted numerically, not as strings.
Using Sorting Flags
The optional flags parameter allows different sorting behaviors like numeric or string comparison.
<?php $mixedKeys = [ "10" => "ten", "2" => "two", "05" => "five", "1" => "one" ]; ksort($mixedKeys, SORT_STRING); print_r($mixedKeys);
With SORT_STRING
, keys are compared as strings. Output shows:
"05", "1", "10", "2". Without this flag, they'd sort numerically.
Sorting Multi-dimensional Arrays
ksort
can sort multi-dimensional arrays by their outer keys.
<?php $users = [ "user3" => ["age" => 25, "name" => "Charlie"], "user1" => ["age" => 30, "name" => "Alice"], "user2" => ["age" => 22, "name" => "Bob"] ]; ksort($users); print_r($users);
This sorts the outer array by user keys while preserving the inner arrays. The output shows user1, user2, user3 in order.
Case-Insensitive Sorting
Combine ksort
with array_change_key_case
for case-
insensitive key sorting.
<?php $colors = [ "Red" => "#FF0000", "green" => "#00FF00", "BLUE" => "#0000FF" ]; $colors = array_change_key_case($colors, CASE_LOWER); ksort($colors); print_r($colors);
First convert all keys to lowercase, then sort. Output shows keys in order: blue, green, red. Original case is lost in this approach.
Best Practices
- Preserve Keys: Use when maintaining key-value pairs is essential.
- Performance: Faster than
asort
for large arrays. - Flags: Choose appropriate sorting flags for your data type.
- Copying: Create a copy if original order must be preserved.
Source
This tutorial covered the PHP ksort
function with practical
examples showing its usage for sorting arrays by keys.
Author
List all PHP Array Functions.