thiCha
Posted on July 16, 2024
Introduced in PHP 7, the Spaceship operator <=> is used to compare two expressions.
It returns:
- 0 if both values are equal
- 1 if left operand is greater
- -1 if right operand is greater
Let’s see it with an example:
echo 2 <=> 2; // Outputs 0
echo 3 <=> 1; // Outputs 1
echo 1 <=> 3; // Outputs -1
echo "b" <=> "b"; // Outputs 0
echo "a" <=> "c"; // Outputs -1
echo "c" <=> "a"; // Outputs 1
// Note: for string comparison, the ASCII value of the characters are used, that is why "c" is greater than "a"
echo "ping" <=> "pong"; // Outputs -1 since "o" is greater than "i"
This operator can be used for sorting arrays:
$numbers = [1, 4, 5, 9, 2, 3];
usort($numbers, function ($a, $b) {
return $a <=> $b; // Sort in ascending order
});
echo print_r($numbers); // Outputs [1,2,3,4,5,9]
usort($numbers, function ($a, $b) {
return $b <=> $a; // Sort in descending order
});
echo print_r($numbers); // [9,5,4,3,2,1]
💖 💪 🙅 🚩
thiCha
Posted on July 16, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.