Skip to content
PHP uksort() Function: Sorting Array Keys with a User‑Defined Comparison Callback

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.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community

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
";
}
?>

Output:

an apple: 3
a banana: 4
the Earth: 2
John: 1

The output shows the array reordered by ignoring leading articles ("a", "an", "the") in the keys.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendPHPphp-functionscustom comparatoruksortarray-sorting
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.