PHP 7 combined comparison operator
PHP 7 introduces a load of new features and some major speed improvements. But one of the coolest new features is the combined comparison operator, or spaceship operator as it’s more lovingly known. Here is what it looks like:
$foo <=> $bar;
You can see where the spaceship nickname comes from, it reminds me of a Tie Interceptor. Besides its cool looks, it’s a really useful operator. Here is how it works.
echo 1 <=> 1; // 0 echo 1 <=> 2; // -1 echo 2 <=> 1; // 1
As you can see in the example above, it is used to compare two values (or variables). If the values are equal, it returns 0. If the left hand operator is greater than the right, it returns -1. If the right hand operator is greater than the left, it returns 1. Pretty nifty. It also works with strings (comparing alphabetically):
echo "a" <=> "a"; // 0 echo "a" <=> "b"; // -1 echo "b" <=> "a"; // 1
Impress your colleagues by using a spaceship operator in your next project. May the force be with you