Summary: in this tutorial, you’ll learn how to use the PHP ksort() function to sort the keys of an associative array.
Introduction to the PHP ksort() function #
The ksort() function sorts the elements of an array by their keys. The ksort() is mainly useful for sorting associative arrays.
The following shows the syntax of the ksort() function:
ksort(array &$array, int $flags = SORT_REGULAR): boolThe ksort() function has two parameters:
$arrayis the input array$flagschanges the sorting behavior using one or more valuesSORT_REGULAR,SORT_NUMERIC,SORT_STRING,SORT_LOCALE_STRING,SORT_NATURAL, andSORT_FLAG_CASE.
To combine the flag values, you use the | operator. For example, SORT_STRING | SORT_NATURAL.
The ksort() function returns true on success or false on failure.
Note that to sort the values of an array in ascending order, you use the sort() function instead.
PHP ksort() function example #
The following example uses the ksort() function to sort an associative array:
<?php
$employees = [
'john' => [
'age' => 24,
'title' => 'Front-end Developer'
],
'alice' => [
'age' => 28,
'title' => 'Web Designer'
],
'bob' => [
'age' => 25,
'title' => 'MySQL DBA'
]
];
ksort($employees, SORT_STRING);
print_r($employees);How it works.
- First, define an associative array of employees with keys are the employee names.
- Second, use the
sort()function to sort the keys of the$employeesarray in ascending order.
Output:
Array
(
[alice] => Array
(
[age] => 28
[title] => Web Designer
)
[bob] => Array
(
[age] => 25
[title] => MySQL DBA
)
[john] => Array
(
[age] => 24
[title] => Front-end Developer
)
)PHP krsort() function #
The krsort() function is like the ksort() function except that it sorts the keys of an array in descending order:
krsort(array &$array, int $flags = SORT_REGULAR): boolSee the following example:
<?php
$employees = [
'john' => [
'age' => 24,
'title' => 'Front-end Developer'
],
'alice' => [
'age' => 28,
'title' => 'Web Designer'
],
'bob' => [
'age' => 25,
'title' => 'MySQL DBA'
]
];
krsort($employees, SORT_STRING);
print_r($employees);Output:
Array
(
[john] => Array
(
[age] => 24
[title] => Front-end Developer
)
[bob] => Array
(
[age] => 25
[title] => MySQL DBA
)
[alice] => Array
(
[age] => 28
[title] => Web Designer
)
)Summary #
- Use the
ksort()function to sort the keys of an associative array in ascending order. - To sort the keys of an associative array, use the
krsort()function.
Thank you for your feedback!