PHP 8 reference · Array Sorting Functions
PHP ksort() Function
Sort an array by key in ascending order, keeping each value with its key.
PHP 8 Since 4.0
Syntax
ksort(array &$array, int $flags = SORT_REGULAR): true
Parameters
| Parameter | Description |
|---|---|
array |
The array to sort (changed in place). |
flags optional |
SORT_REGULAR, SORT_NUMERIC, SORT_STRING, SORT_NATURAL, optionally | SORT_FLAG_CASE. Default: SORT_REGULAR |
Return value
Always true.
Examples
<?php
$config = ["timeout" => 30, "debug" => false, "name" => "app"];
ksort($config);
print_r($config);
Output
Array
(
[debug] =>
[name] => app
[timeout] => 30
)<?php
$byYear = [2026 => "now", 1999 => "then", 2010 => "between"];
ksort($byYear);
echo implode(", ", $byYear), "\n";
Output
then, between, now
Version history
Related
krsort()· Sort an array by key in descending order, keeping each value with its key.uksort()· Sort an array by key with your own comparison function, keeping values with their keys.asort()· Sort an array by value in ascending order, keeping each key attached to its value. Ideal for name => score maps.sort()· Sort an array's values in ascending order, in place. Keys are discarded and the result is renumbered from 0.- PHP Arrays · tutorial
- PHP Array Functions · tutorial