Spaceship
The spaceship operator (<=>) is a comparison operator introduced in PHP 7 that returns -1, 0, or 1 depending on the relative values of its operands.
If the operand on the left is less than the operand on the right, the operator returns -1. If the operands are equal, it returns 0. If the operand on the left is greater than the operand on the right, it returns 1.
This operator can be useful when sorting arrays or performing other kinds of comparison tasks.
Example:
<?php
$x = 10;
$y = 20;
$result1 = $x <=> $y; // -1
$result2 = $y <=> $x; // 1
$result3 = $x <=> $x; // 0
echo $result1 . "\n";
echo $result2 . "\n";
echo $result3 . "\n";
?>
You can also use the spaceship operator when sorting arrays with the usort() function:
<?php
$array = [3, 2, 1];
usort($array, function($a, $b) {
return $a <=> $b;
});
print_r($array); // [1, 2, 3]
?>