PHP uksort() Function: Sorting Array Keys with a User‑Defined Comparison Callback
The article explains PHP's uksort() function, which sorts an array by its keys using a custom comparison function, details its signature, parameters, return values, provides a complete example with code and shows the resulting output after reordering the keys.
The uksort() function in PHP sorts an array by its keys using a user‑provided comparison callback, allowing custom ordering criteria.
Signature: bool uksort(array &$array, callable $cmp_function) .
Parameters: $array – the input array; $cmp_function – a callable that must return an integer less than, equal to, or greater than zero when the first argument is respectively less than, equal to, or greater than the second.
Return value: TRUE on success, FALSE on failure.
Example:
<?php
function cmp($a, $b) {
$a = preg_replace('@^(a|an|the) @', '', $a);
$b = preg_replace('@^(a|an|the) @', '', $b);
return strcasecmp($a, $b);
}
$a = array(
"John" => 1,
"the Earth" => 2,
"an apple" => 3,
"a banana" => 4
);
uksort($a, "cmp");
foreach ($a as $key => $value) {
echo "$key: $value\n";
}
?>Output:
an apple: 3
a banana: 4
the Earth: 2
John: 1The output shows the array reordered by ignoring leading articles ("a", "an", "the") in the keys.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.