ksort()
ksort() — Sort an array by key in ascending order.
Built-in function of PHP 8.5. The manual lists it as available in PHP 4, PHP 5, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.
Signature
ksort(array &$array, int $flags = SORT_REGULAR): true
Parameters
| Parameter | Type | What it takes |
|---|---|---|
| &$array | array | The input array. |
| $flags | int | Sorting type flags: SORT_REGULAR - compare items normally; the details are described in the comparison operators section SORT_NUMERIC - compare items numerically SORT_STRING - compare items as strings SORT_LOCALE_STRING - compare items as strings, based on the current locale. It uses the locale, which can be changed using setlocale() SORT_NATURAL - compare items as strings using "natural ordering" like natsort() ... |
Return value
Always returns true.
Example
A runnable snippet:
$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple"); ksort($fruits); foreach ($fruits as $key => $val) { echo "$key = $val\n"; }
Output:
a = orange b = banana c = apple d = lemon
Changelog
| Version | Change |
|---|---|
| 8.2.0 | The return type is true now; previously, it was bool. |
| 8.2.0 | This function now does numeric string comparison under SORT_REGULAR using the standard PHP 8 rules. |
See also
All PHP 8.5 built-in functions
Reference card built from the PHP manual page ksort() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.