PHP usort() Function

The usort() function in PHP allows you to sort an array using a user-defined comparison function. Unlike the sort() function, which sorts an array in ascending order, the usort() function sorts an array based on a custom sorting logic provided by the user.

In simple words, the usort() function allows you to define your own comparison logic. This gives greater flexibility for handling complex sorting requirements compared to the sort() function or other built-in sorting functions like asort(), ksort(), etc.

The usort() function is especially useful in PHP when the default sorting behavior, such as ascending or descending order, is not sufficient for your needs.

For example, you can sort an array of strings by their length, sort an array of objects by a specific property, or even sort by multiple criteria. Suppose you have an array of objects representing users, and you want to sort them by age and then by name. You can make this easy with the help of usort() function.

Syntax of usort() Function in PHP


The general syntax to define the usort() function is as follows:

usort(array &$array, callable $callback): bool

In the above syntax of usort() function,

  • $array represents the name of an array that has to be sorted.
  • $callback is a user-defined comparison function that determines the sorting order of the elements. This function accepts two parameters, which represent two array elements being compared. The 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 usort() function returns true on successful operation. Otherwise, it returns false on failure.

Basic Example of usort() Function


Example 1: Let’s write a simple PHP program in which we have an array of numeric values and we will sort it in ascending order using custom sorting logic.

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

In this example, the comparison function subtracts the second element from the first. If the result is negative, it means the first element is smaller, and it should come before the second element. If the result is positive, the first element is larger and should come after the second element. If the result is zero, the elements are considered equal.

Example 2: Write a PHP program to sort an array in descending order. To sort an array in descending order, simply reverse the comparison logic like this:

<?php
$numbers = [5, 2, 9, 1, 7];
function compareDesc($a, $b) {
   return $b - $a;
}
usort($numbers, 'compareDesc');
print_r($numbers);
?>
Output:
     Array
    (
      [0] => 9
      [1] => 7
      [2] => 5
      [3] => 2
      [4] => 1
    )

Sorting Array based on Length


Example 3: Let us write a PHP program in which we have an array of strings and we want to sort them based on their lengths using usort() function.

<?php
$fruits = ['apple', 'banana', 'cherry', 'date'];
function compare($a, $b){
    return strlen($a) - strlen($b);
}
usort($fruits, "compare");
print_r($fruits);
?>
Output:
      Array
     (
       [0] => date
       [1] => apple
       [2] => banana
       [3] => cherry
     )

In this example, we have defined the comparison function compare() which compares the length of the strings rather than their alphabetical order. As a result, the array is sorted by the length of the strings in ascending order.

Sorting an Associative Array by Value


The usort() function in PHP is mainly used with indexed arrays because it does not preserve array keys. However, you can use it to sort an associative array by values.

Example 4:

<?php
$students = [
   'Alice' => 85,
   'Bob' => 92,
   'Charlie' => 78,
   'Shanvika' => 65
];
function compare($a, $b){
    return $a - $b;
}
usort($students, 'compare');
print_r($students);
?>
Output:
      Array
      (
        [0] => 65
        [1] => 78
        [2] => 85
        [3] => 92
      )

In this example, we have sorted an associative array by its values in ascending order using usort() function. However, the order of keys is lost. If you need to preserve the keys, use uasort() function, which maintains the key-value associations.

Sorting an Array of Strings


Example 5: Let’s write a PHP program to sort an array of strings alphabetically using usort() function.

<?php
$names = ["John", "Alice", "Bob", "Mark"];
function compare($a, $b){
    return strcmp($a, $b);
}
usort($names, 'compare');
print_r($names);
?>
Output:
      Array
      (
        [0] => Alice
        [1] => Bob
        [2] => John
        [3] => Mark
      )

Sorting Multidimensional Arrays using PHP usort()


Example 6: Let’s write a PHP program where we have an associative array of students with name and score keys. We will sort students by their scores in descending order.

<?php
$students = [
   ['name' => 'Alice', 'score' => 80],
   ['name' => 'Bob', 'score' => 95],
   ['name' => 'Charlie', 'score' => 75],
   ['name' => 'David', 'score' => 92],
];

usort($students, function($a, $b) {
    return $b['score'] - $a['score'];
});
print_r($students);
?>
Output:
    Array
    (
        [0] => Array
        (
            [name] => Bob
            [score] => 95
        )

        [1] => Array
        (
            [name] => David
            [score] => 92
        )

        [2] => Array
        (
            [name] => Alice
            [score] => 80
        )

        [3] => Array
        (
            [name] => Charlie
            [score] => 75
        )
    )

Sorting an Array of Objects


Example 7: Let’s write a PHP program in which we will sort an array of objects.

<?php
class Employee {
  public $name;
  public $age;

  public function __construct($name, $age) {
    $this->name = $name;
    $this->age = $age;
  }
}

$employees = [
   new Employee("Alice", 20),
   new Employee("Bob", 35),
   new Employee("John", 23)
];
function compareEmp($a, $b){
    return $a->age - $b->age;
}
usort($employees, 'compareEmp');

foreach ($employees as $employee) {
    echo "$employee->name - $employee->age\n";
}
?>
Output:
      Alice - 20
      John - 23
      Bob - 35

Sorting with Multiple Criteria


Sometimes, you may need to sort an array by multiple criteria. Single criterion is not enough while sorting an array. Let’s take an example in which we will sort employees first by age and then by name alphabetically , if ages are the same.

Example 8:

<?php
$employees = [
    ['name' => 'Alice', 'age' => 25],
    ['name' => 'Bob', 'age' => 30],
    ['name' => 'Charlie', 'age' => 25],
];

usort($employees, function($a, $b) {
   if ($a['age'] == $b['age']) {
      return strcmp($a['name'], $b['name']);
   }
   return $a['age'] - $b['age'];
});
print_r($employees);
?>
Output:
    Array
    (
        [0] => Array
        (
            [name] => Alice
            [age] => 25
        )

        [1] => Array
        (
            [name] => Charlie
            [age] => 25
        )

        [2] => Array
        (
            [name] => Bob
            [age] => 30
        )
     )

The usort() function in PHP is a versatile tool that allows you to sort arrays using custom comparison logic. Whether you’re sorting indexed arrays, associative arrays (without preserving keys), or arrays of objects, usort() provides the flexibility to implement complex sorting criteria.

By defining a custom comparison function, you can sort arrays based on numerical values, strings, and object properties. However, for associative arrays where key preservation is necessary, uasort() function should be used, which we will understand in the next tutorial.