What is the function of the usort function in PHP and how can it be used to sort arrays based on specific criteria?
The usort function in PHP is used to sort an array based on a user-defined comparison function. This allows you to sort arrays based on specific criteria that may not be supported by the built-in sorting functions. To use usort, you need to define a custom comparison function that compares two elements of the array and returns -1, 0, or 1 based on their relationship.
// Example of using usort to sort an array of numbers in descending order
$array = [5, 2, 8, 1, 3];
usort($array, function($a, $b) {
if ($a == $b) {
return 0;
}
return ($a > $b) ? -1 : 1;
});
print_r($array);