Using uasort() to Sort Arrays with User‑Defined Comparison Functions in PHP

This article explains PHP's uasort() function, detailing its purpose of sorting associative arrays while preserving keys, describing its parameters, providing a custom comparison function example, and demonstrating the resulting sorted array output.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Using uasort() to Sort Arrays with User‑Defined Comparison Functions in PHP

The uasort() function in PHP sorts an array while keeping the association between keys and values, making it ideal for situations where the order of elements is important and a custom comparison logic is required.

Function signature :

bool uasort(array &$array, callable $cmp_function)

Description

The function takes an input array and a user‑defined comparison function. It reorders the array based on the comparison results while preserving the original keys.

Parameters array: The input array to be sorted. cmp_function: A callable that defines how two elements are compared. See usort() and uksort() for examples.

Return value

Returns TRUE on success, or FALSE on failure.

Example

<?php
// Comparison function
function cmp($a, $b) {
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

// Array to be sorted
$array = array(
    'a' => 4,
    'b' => 8,
    'c' => -1,
    'd' => -9,
    'e' => 2,
    'f' => 5,
    'g' => 3,
    'h' => -4
);

print_r($array);
// Sort and print the resulting array
uasort($array, 'cmp');
print_r($array);
?>

Output

Array
(
    [a] => 4
    [b] => 8
    [c] => -1
    [d] => -9
    [e] => 2
    [f] => 5
    [g] => 3
    [h] => -4
)
Array
(
    [d] => -9
    [h] => -4
    [c] => -1
    [e] => 2
    [g] => 3
    [a] => 4
    [f] => 5
    [b] => 8
)
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.

Backendphp-functionsarray sortinguasort
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
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.