ksort
PHP function
Edit on GitHub ✎
(PHP 4, PHP 5, PHP 7, PHP 8)
Sort an array by key in ascending order
Description
ksort(array $array, int $flags = SORT_REGULAR): true
Sorts array in place by keys in ascending order.
Sort-unstable Reset-index
Parameters
arrayThe input array.
Return Values
Always
Changelog
| Version | Description |
|---|---|
| 8.2.0 | This function now does numeric string comparison under SORT_REGULAR using the standard PHP 8 rules. |
Examples
ksort() example
php
<?php
$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
ksort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?>The above example will output:
output
a = orange
b = banana
c = apple
d = lemonksort() with int keys
php
<?php
$a = [0 => 'First', 2 => 'Last', 1 => 'Middle'];
var_dump($a);
ksort($a);
var_dump($a);
?>The above example will output:
output
array(3) {
[0]=>
string(5) "First"
[2]=>
string(4) "Last"
[1]=>
string(6) "Middle"
}
array(3) {
[0]=>
string(5) "First"
[1]=>
string(6) "Middle"
[2]=>
string(4) "Last"
}