What is the PHP sort array by key?

Sorting is an algorithmic approach to ordering items. All linear data structures can be arbitrarily ordered: the PHP array is no exception. The PHP arraya hash table—is perhaps the language's quintessential composite data structure. It is a dynamic artifact that can be used as a traditional numeric array, associative array, multidimensional array, or any combination of the options mentioned above. Much like the rest of the language, PHP's array structure has evolved steadily through several iterations to offer competitive performance.

As with most array implementations, the items in PHP arrays have indexes with which it is possible to access their values. The indexes are either of a numeric or string type. Sorting an array by key, therefore, is a task that involves ordering a PHP array by evaluating the properties of its keys. PHP offers functions that make sorting arrays by key efficient.

The ksort and krsort functions

The ksort and krsort functions make it possible to sort array keys, and transitively, array elements, in ascending and descending order respectively. For arrays with string keys, the ksort and krsort functions produce respective alphabetical and reverse-alphabetical key orderings. With a custom function like custom_sort in the snippet to follow, it is possible to abstract the use of the aforestated array key sorting functions.

Example

<?php
function custom_sort(array $list, bool $asc = true): array
{
$asc ? ksort($list) : krsort($list);
return $list;
}
$numeric = [
12 => 'baz',
2 => 'foo',
5 => 'bar',
];
$assoc = [
'foo' => 'foo',
'baz' => 'baz',
'bar' => 'bar',
];
var_dump(
custom_sort($assoc), // sort ascending
custom_sort($assoc, false), // sort descending
custom_sort($numeric), // sort ascending
custom_sort($numeric, false), // sort descending
);

Explanation

The custom_sort function sorts, at a user's discretion, arrays by key in either ascending or descending order (alphabetical or reverse-alphabetical order for string data). It takes two arguments, a list to sort and a boolean flag with which to specify the intended order (which is ascending by default). The custom_sort function signature is such that depending on the user's choice, it accordingly invokes the ksort or krsort functions and returns a sorted list. It is worth noting that ksort and krsort do not constitute the return expression because they are only invokable by reference.

Example

Sorting the associative and numeric arrays, $assoc and $numeric, via the custom_sort function in ascending and descending order.

// sort $assoc in ascending order
array(3) {
["bar"]=>
string(3) "bar"
["baz"]=>
string(3) "baz"
["foo"]=>
string(3) "foo"
}
// sort $assoc in descending order
array(3) {
["foo"]=>
string(3) "foo"
["baz"]=>
string(3) "baz"
["bar"]=>
string(3) "bar"
}
// sort $numeric in ascending order
array(3) {
[2]=>
string(3) "foo"
[5]=>
string(3) "bar"
[12]=>
string(3) "baz"
}
// sort $numeric in descending order
array(3) {
[12]=>
string(3) "baz"
[5]=>
string(3) "bar"
[2]=>
string(3) "foo"
}
Output of ksort and krsort

The uksort function

Another option for sorting a PHP array by key is the native uksort function. uksort is especially intriguing because it affords a user complete control of the sorting rules unlike ksort and krsort that each provide a singular approach to ordering array keys. Via a callback function, it is possible to specify arbitrary array key sorting guidelines. uksort is, like the functions from the previous section, a pass-by-reference function that ought not to be called in the return statement of a wrapper function. As with the previous section, an arbitrary function—named custom_sort_cb for this section—should suffice to demonstrate the sorting powers of uksort.

Example

The snippet below showcases a simple application of discretionary array key ordering.

<?php
function custom_sort_cb(array $list, callable $callback): array
{
uksort($list, $callback);
return $list;
}
$assoc = [
'food' => 'food',
'bass' => 'bass',
'battery' => 'battery',
];
var_dump(
custom_sort_cb(
$assoc,
fn ($current, $next) => strncasecmp($current, $next, 3),
),
);

Explanation

The approach to writing the custom wrapper custom_sort_cb is the same as that utilized in writing the wrapper in the previous section. The sorting logic in the function passed to uksort is perhaps the most compelling part of this segment. Per the snippet above, the arrow function passed to custom_sort_cb —and ultimately, to uksort—iteratively performs a binary non-case sensitive comparison between the current key element and the next. Only the first three characters of each key, and not the whole key, are compared. If a match is found between the current key and the next, then the order is maintained, otherwise, a comparison between the positive result of a comparison produces an alphabetical order like that in the snippet below.

array(3) {
["bass"]=>
string(4) "bass"
["battery"]=>
string(7) "battery"
["food"]=>
string(4) "food"
}
Output of uksort
Copyright ©2024 Educative, Inc. All rights reserved