What is the purpose of using the usort function in PHP and how does it work?

The usort function in PHP is used to sort an array by values using a user-defined comparison function. This allows for custom sorting logic to be applied to the array elements. By using usort, you can define how the elements should be compared and sorted, giving you more control over the sorting process.

// Example of using usort to sort an array of numbers in descending order
$numbers = [5, 2, 8, 1, 9];

usort($numbers, function($a, $b) {
    if ($a == $b) {
        return 0;
    }
    return ($a > $b) ? -1 : 1;
});

print_r($numbers);