usort vs uasort: Sorting PHP Associative Arrays
When sorting arrays in PHP using custom comparison logic, developers
often choose between the usort() and uasort()
functions. While both functions allow you to define your own sorting
criteria using a callback function, they behave very differently
regarding how they handle array keys. This article explains the
fundamental differences between usort() and
uasort(), demonstrating how each function affects
associative arrays so you can choose the correct tool for your PHP
projects.
The Core Difference
The main distinction between these two functions lies in key preservation:
usort()sorts the array by value using a user-defined comparison function and discards the original keys, assigning new numerical keys starting from 0.uasort()sorts the array by value using a user-defined comparison function and maintains the original key-value associations.
How usort() Works
Use usort() when the original keys of your array do not
matter, such as in simple list arrays (indexed arrays). If you pass an
associative array to usort(), all your custom string or
non-sequential keys will be lost and replaced with sequential
integers.
Example of usort()
$fruits = [
'apple' => 3,
'banana' => 1,
'cherry' => 2
];
// Sort ascending by value
usort($fruits, function($a, $b) {
return $a <=> $b;
});
print_r($fruits);Output:
Array
(
[0] => 1
[1] => 2
[2] => 3
)
Note that the original keys (apple,
banana, cherry) have been completely destroyed
and replaced with 0, 1, and
2.
How uasort() Works
Use uasort() when sorting associative arrays where the
keys contain essential relationship data (such as IDs, usernames, or
configuration names) that must remain linked to their respective
values.
Example of uasort()
$fruits = [
'apple' => 3,
'banana' => 1,
'cherry' => 2
];
// Sort ascending by value while maintaining keys
uasort($fruits, function($a, $b) {
return $a <=> $b;
});
print_r($fruits);Output:
Array
(
[banana] => 1
[cherry] => 2
[apple] => 3
)
The array is successfully sorted by the numeric values, but the original associative keys remain securely mapped to their values.
Summary: When to Use Which?
| Feature | usort() |
uasort() |
|---|---|---|
| Primary Use Case | Indexed arrays (lists) | Associative arrays |
| Key Preservation | No (Re-indexes to 0, 1, 2…) | Yes (Keeps original keys) |
| Custom Comparison | Yes | Yes |
| Return Value | true on success,
false on failure |
true on success,
false on failure |