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.
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
)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.