ksort
Sorts an array by key.
Syntax
ksort(array &$array, int $flags = SORT_REGULAR): trueParameters
| Parameter | Type | Description |
|---|---|---|
| $array | array | The array being sorted. |
| $flags | int | Optional. The comparison mode. |
Return value
trueAlways `true`; the array itself is modified.
Examples
Keys in alphabetical order:
<?php
$stock = ['pear' => 5, 'apple' => 12, 'plum' => 3];
ksort($stock);
echo implode(', ', array_keys($stock));Output:
apple, pear, plumIn reverse order — krsort():
<?php
$years = [2023 => 'a', 2025 => 'c', 2024 => 'b'];
krsort($years);
echo implode(', ', array_keys($years));Output:
2025, 2024, 2023Notes
The values stay attached to their keys.
See also
Related recipes
In the tutorial
- Sorting arrays — Sorting in PHP — sort, rsort, asort, ksort, a custom rule with usort and the spaceship operator.