0
0
PhpHow-ToBeginner · 3 min read

How to Use usort in PHP: Sorting Arrays with Custom Functions

Use usort in PHP to sort an array by providing a custom comparison function that defines the order. The function takes the array and a callback that compares two elements, returning -1, 0, or 1 to set their order.
📐

Syntax

The usort function sorts an array by values using a user-defined comparison function.

  • array: The array you want to sort (passed by reference).
  • callback: A function that compares two values and returns an integer.

The callback should return -1 if the first value is less, 1 if greater, or 0 if equal.

php
bool usort(array &$array, callable $callback)
💻

Example

This example sorts an array of numbers in ascending order using usort with a custom comparison function.

php
<?php
$numbers = [4, 2, 8, 6];
usort($numbers, function($a, $b) {
    if ($a == $b) return 0;
    return ($a < $b) ? -1 : 1;
});
print_r($numbers);
?>
Output
Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 )
⚠️

Common Pitfalls

Common mistakes include:

  • Not returning -1, 0, or 1 exactly, which can cause unexpected sorting.
  • Modifying the array inside the comparison function, which leads to errors.
  • Using sort or asort when a custom order is needed instead of usort.
php
<?php
// Wrong: returning boolean instead of -1,0,1
$items = [3, 1, 2];
usort($items, function($a, $b) {
    return $a < $b; // returns true or false, not -1,0,1
});
print_r($items);

// Right: correct return values
usort($items, function($a, $b) {
    if ($a == $b) return 0;
    return ($a < $b) ? -1 : 1;
});
print_r($items);
?>
Output
Array ( [0] => 3 [1] => 1 [2] => 2 ) Array ( [0] => 1 [1] => 2 [2] => 3 )
📊

Quick Reference

usort sorts arrays with a custom comparison function.

  • Pass array by reference.
  • Comparison function must return -1, 0, or 1.
  • Use for flexible sorting rules.
FunctionDescription
usort(array, callback)Sorts array by values using callback
Callback return -1First element is less than second
Callback return 0Elements are equal
Callback return 1First element is greater than second

Key Takeaways

Use usort to sort arrays with a custom comparison function in PHP.
The comparison function must return -1, 0, or 1 to define order.
Always pass the array by reference to usort.
Avoid returning boolean values in the comparison function.
usort is ideal for complex sorting rules beyond simple ascending or descending.