How can the spaceship operator be utilized in PHP for sorting arrays?
The spaceship operator (<=>) in PHP can be utilized for sorting arrays by providing a simple and concise way to compare values. It returns -1 if the left operand is less than the right, 0 if they are equal, and 1 if the left operand is greater than the right. This makes it easy to sort arrays in ascending or descending order based on a specific key or value.
// Example of sorting an array of numbers in ascending order using the spaceship operator
$numbers = [4, 2, 8, 5, 1];
usort($numbers, function($a, $b) {
return $a <=> $b;
});
print_r($numbers);