PHP uasort() Function
The uasort() function in PHP is a built-in function that sorts an associative array by values using a user-defined comparison function, while preserving the original keys.
Here, “ua” in uasort() function stands for “user-defined associative sort”, which indicates two key facts:
- “u”: It uses a user-defined comparison function.
- “a”: It maintains the association between keys and values in the array.
This features makes uasort() function different from other sorting functions, such as usort() and asort() functions. The usort() function uses a user-defined comparison function, but does not preserve keys. While the asort() function preserves keys, but uses the built-in comparison provided by PHP.
Syntax of uasort() Function in PHP
The general syntax to define uasort() function in PHP is as follows:
uasort(array &$array, callable $callback): bool
In the above syntax of uasort() function,
- $array represents the name of an associative array that has to be sorted passed by reference. This means the original array is modified directly.
- $callback is a user-defined comparison function. This function must accept two parameters, which represent two array elements being compared. The comparison function will return:
- A negative number if the first element is less than the second.
- Zero if the two elements are equal.
- A positive number if the first element is greater than the second.
The uasort() function returns true on successful sort. Otherwise, it returns false if the sorting operation fails.
When to Use uasort() Function in PHP?
You can use PHP uasort() function when you need to:
- Sort an associative array by values (not keys).
- Preserve the original keys of the array (key association).
- Define custom sorting rules that are more complex than what built-in sort flags can handle.
For example, if you want to sort product ratings, dates, or complex objects in a custom order while preserving the array’s keys, uasort() is the best choice.
Basic Example of uasort() Function
Let’s take a simple example to understand how uasort() function works.
Example 1:
<?php
$fruits = [
"apple" => 3,
"banana" => 5,
"orange" => 2,
"grapes" => 4
];
uasort($fruits, function($a, $b) {
return $a - $b; // Ascending order based on values.
});
print_r($fruits);
?>
Output: Array ( [orange] => 2 [apple] => 3 [grapes] => 4 [banana] => 5 )
In the above example, uasort() function sorted the array in ascending order based on the values, and the original keys were preserved.
Sorting in Descending Order
To sort an associative array in descending order, simply reverse the comparison in the callback function like this:
uasort($fruits, function($a, $b) {
return $b - $a; // Descending order.
});
Output: Array ( [banana] => 5 [grapes] => 4 [apple] => 3 [orange] => 2 )
Sorting by String Length
Suppose we have an associative array of usernames and we want to sort them by the length of the username (based on value).
Example 2:
<?php
$usernames = [
"user1" => "alice",
"user2" => "bob",
"user3" => "christopher",
"user4" => "dan"
];
// Sort by string length.
uasort($usernames, function($a, $b) {
return strlen($a) - strlen($b);
});
print_r($usernames);
?>
Output: Array ( [user2] => bob [user4] => dan [user1] => alice [user3] => christopher )
Sorting Complex Data Structures
Let’s take a real-world example where we have a list of products, and we want to sort them by their price.
Example 3:
<?php
$products = [
"p1" => ["name" => "Laptop", "price" => 999],
"p2" => ["name" => "Smartphone", "price" => 499],
"p3" => ["name" => "Tablet", "price" => 299],
"p4" => ["name" => "Desktop", "price" => 700]
];
// Using spaceship operator for numeric comparison.
uasort($products, function($a, $b) {
return $a["price"] <=> $b["price"];
});
print_r($products);
?>
Output: Array ( [p3] => Array ( [name] => Tablet [price] => 299 ) [p2] => Array ( [name] => Smartphone [price] => 499 ) [p4] => Array ( [name] => Desktop [price] => 700 ) [p1] => Array ( [name] => Laptop [price] => 999 ) )
In this example, we have used spaceship operator (<=>), which simplifies comparison functions. This operator was introduced in PHP 7+ version. The spaceship operator returns:
- 0 if the values are equal.
- -1 if if the left-hand side is less than the right-hand side.
- 1 if the left-hand side is greater than the right-hand side.
Example 4:
// With spaceship operator.
echo 5 <=> 10; // Outputs: -1
echo 10 <=> 10; // Outputs: 0
echo 15 <=> 10; // Outputs: 1
Comparison with Other Sorting Functions
Function | Sorts By | Maintain Key Association | Comparison Method |
---|---|---|---|
sort() | Values | No | Built-in |
asort() | Values | Yes | Built-in |
ksort() | Keys | Yes | Built-in |
usort() | Values | No | User-defined |
uksort() | Keys | Yes | User-defined |
uasort() | Values | Yes | User-defined |