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

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

ksort(array &$array, int $flags = SORT_REGULAR): true

Parameters

ParameterDescription
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

Sort by keyTry it yourself
<?php
$config = ["timeout" => 30, "debug" => false, "name" => "app"];
ksort($config);
print_r($config);

Output

Array
(
    [debug] => 
    [name] => app
    [timeout] => 30
)
Numeric keysTry it yourself
<?php
$byYear = [2026 => "now", 1999 => "then", 2010 => "between"];
ksort($byYear);
echo implode(", ", $byYear), "\n";

Output

then, between, now

Version history

VersionChange
PHP 4.0Added
PHP 8.0Sorting is stable: elements that compare equal keep their original order.
PHP 8.2The return type is true (it was bool).

Was this page helpful?