PHP usort() - Custom Array Sort
Learn PHP usort() function. Sort arrays using user-defined comparison function for custom sorting logic.
Introduction
Sorting arrays is a common task in PHP development. While PHP offers built-in sorting functions like sort() and asort() for standard sorting, there are scenarios where you need to sort arrays with custom rules. This is where usort() shines.
The PHP usort() function allows you to sort an array by defining your own comparison logic through a callback function. This tutorial, written by a PHP sorting specialist with over 14 years of experience, will guide you through understanding, implementing, and mastering usort().
Prerequisites
- Basic understanding of PHP.
- Familiarity with PHP arrays.
- Knowledge of anonymous functions (closures) or callbacks in PHP.
- PHP version 5.3+ (supports anonymous functions), but
usort()exists since PHP 4.
Setup Steps
- Ensure PHP is installed and configured on your system.
- Create a PHP file, for example,
usort-demo.php. - Start with an unsorted array to apply the
usort()function. - Define a user comparison callback function.
- Call
usort()with the array and callback. - Print the sorted array to verify results.
What is the PHP usort() Function?
usort() is a built-in PHP function that sorts an array by values using a user-defined comparison function. The comparison function must return:
- Less than 0, if first argument is less than the second.
- 0, if both arguments are equal.
- Greater than 0, if first argument is greater than the second.
Syntax:
bool usort(array &array, callable $callback)
- array: The input array passed by reference; it will be sorted in place.
- callback: The comparison function with two parameters.
Example 1: Sorting Numbers in Ascending Order
<?php
$numbers = [5, 3, 9, 1, 7];
usort($numbers, function($a, $b) {
return $a - $b; // ascending order
});
print_r($numbers);
?>
Output:
Array
(
[0] => 1
[1] => 3
[2] => 5
[3] => 7
[4] => 9
)
Explanation:
The anonymous function compares two numbers and sorts the array in ascending order by subtracting the values.
Example 2: Sorting an Array of Associative Arrays by a Specific Key
<?php
$users = [
['name' => 'John', 'age' => 25],
['name' => 'Jane', 'age' => 22],
['name' => 'Dave', 'age' => 30],
];
usort($users, function($a, $b) {
return $a['age'] - $b['age']; // sort by age ascending
});
print_r($users);
?>
Output:
Array
(
[0] => Array
(
[name] => Jane
[age] => 22
)
[1] => Array
(
[name] => John
[age] => 25
)
[2] => Array
(
[name] => Dave
[age] => 30
)
)
Explanation:
This callback sorts the $users array by the age key in ascending order.
Example 3: Case-Insensitive String Sorting
<?php
$words = ['banana', 'Apple', 'cherry', 'apple'];
usort($words, function($a, $b) {
return strcasecmp($a, $b); // case-insensitive comparison
});
print_r($words);
?>
Output:
Array
(
[0] => Apple
[1] => apple
[2] => banana
[3] => cherry
)
Explanation:
Here, usort() sorts strings ignoring their case using strcasecmp().
Best Practices for Using usort()
- Always return an integer from the callback (-1, 0, 1 or numeric false/positive).
- Use strict typing if possible to avoid unexpected comparison results.
- Remember that usort() sorts in place, so your original array is overwritten.
- Ensure the callback handles all data types your array might contain to avoid errors.
- Use built-in functions like
strcmp(),strcasecmp(), or arithmetic operators for efficient comparisons.
Common Mistakes When Using usort()
- Returning a boolean value from the callback instead of integer comparison value.
- Passing a non-callable value as the callback parameter.
- Modifying the array inside the comparison function (leads to unpredictable behavior).
- Ignoring that
usort()reindexes array keys β original keys are lost. - Not handling equal values correctly, which may affect stable sorting.
Interview Questions
Junior-Level Questions
- Q1: What is the purpose of the PHP
usort()function?
A: To sort an array using a user-defined comparison function. - Q2: How does the comparison function used in
usort()work?
A: It takes two parameters and returns an integer less than, equal to, or greater than zero to determine order. - Q3: Does
usort()preserve the array keys?
A: No, it reindexes the array and loses original keys. - Q4: Can
usort()be used to sort associative arrays?
A: Yes, but it sorts by values and reindexes keys. - Q5: What happens if the comparison function returns values other than integer?
A: PHP expects an integer; non-integers may cause improper sorting.
Mid-Level Questions
- Q1: How would you implement a descending order sort with
usort()?
A: By reversing comparison logicβfor example, return$b - $afor numbers. - Q2: Why might you choose
usort()oversort()orasort()?
A: When you need custom sorting logic or to sort complex data. - Q3: Can
usort()be used to sort multidimensional arrays?
A: Yes, by writing a comparison function that compares specific keys or values. - Q4: What is the difference between
usort()anduksort()?
A:usort()sorts by values with user comparison;uksort()sorts by keys using user comparison. - Q5: How to ensure
usort()produces a stable sort?
A: PHP'susort()does not guarantee stable sort; custom logic or other algorithms may be needed.
Senior-Level Questions
- Q1: How does
usort()behave internally with complex callback functions?
A: It repeatedly calls the callback to compare elements during sort, so efficient callbacks are critical. - Q2: Can you optimize sorting large datasets with
usort()?
A: Use optimized comparison logic and consider alternative structures or algorithms for performance. - Q3: How do you handle sorting objects by multiple properties using
usort()?
A: Compose the comparison function to check each property in sequence and return accordingly. - Q4: Discuss the implications of using
usort()on associative arrays in terms of key preservation.
A: Keys are lost becauseusort()reindexes; useuasort()if keys must persist. - Q5: How would you implement a locale-aware string sorting with
usort()?
A: Use PHP'scollator_compare()from the intl extension in the comparison callback.
Frequently Asked Questions (FAQ)
Q1: Does usort() maintain key associations in arrays?
No. usort() reindexes the array β original keys are lost after sorting.
Q2: What is the difference between usort() and uasort()?
usort() reindexes the array during sorting, whereas uasort() maintains key associations.
Q3: Is the callback function for usort() required to be a named function?
No, it can be a named function, a closure (anonymous function), or a callable in any valid PHP form.
Q4: What happens if the comparison function returns inconsistent values?
The sorting behavior becomes undefined and may produce unexpected results.
Q5: Can usort() be used to sort objects?
Yes, as long as the callback function compares the objects appropriately.
Conclusion
The usort() function in PHP is a powerful tool to perform custom sorting on arrays by leveraging user-defined comparison logic. It gives you full control over how elements should be ordered, whether you're sorting numbers, strings, associative arrays, or even objects.
Always remember to implement the comparison callback carefully and keep in mind that usort() modifies the original array and reindexes keys. By mastering usort(), you will be better equipped to handle complex sorting needs in your PHP applications.