Spaceship operator 🚀 in PHP

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; // Ou…


This content originally appeared on DEV Community and was authored by thiCha

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]


This content originally appeared on DEV Community and was authored by thiCha


Print Share Comment Cite Upload Translate Updates
APA

thiCha | Sciencx (2024-07-16T11:00:23+00:00) Spaceship operator 🚀 in PHP. Retrieved from https://www.scien.cx/2024/07/16/spaceship-operator-%f0%9f%9a%80-in-php/

MLA
" » Spaceship operator 🚀 in PHP." thiCha | Sciencx - Tuesday July 16, 2024, https://www.scien.cx/2024/07/16/spaceship-operator-%f0%9f%9a%80-in-php/
HARVARD
thiCha | Sciencx Tuesday July 16, 2024 » Spaceship operator 🚀 in PHP., viewed ,<https://www.scien.cx/2024/07/16/spaceship-operator-%f0%9f%9a%80-in-php/>
VANCOUVER
thiCha | Sciencx - » Spaceship operator 🚀 in PHP. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/07/16/spaceship-operator-%f0%9f%9a%80-in-php/
CHICAGO
" » Spaceship operator 🚀 in PHP." thiCha | Sciencx - Accessed . https://www.scien.cx/2024/07/16/spaceship-operator-%f0%9f%9a%80-in-php/
IEEE
" » Spaceship operator 🚀 in PHP." thiCha | Sciencx [Online]. Available: https://www.scien.cx/2024/07/16/spaceship-operator-%f0%9f%9a%80-in-php/. [Accessed: ]
rf:citation
» Spaceship operator 🚀 in PHP | thiCha | Sciencx | https://www.scien.cx/2024/07/16/spaceship-operator-%f0%9f%9a%80-in-php/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.