Deepak Mankotia Deepak Mankotia - 9 months ago 55
PHP Question

What is <=> (the 'Spaceship' Operator) in PHP 7?

PHP 7, which will come out in November this year will introduce the Spaceship (<=>) operator. What is it and how does it work?

This question already has an answer in our general reference question about PHP operators.

Answer Source

This <=> operator will offer combined comparison in that it will :

Return 0 if values on either side are equal
Return 1 if value on the left is greater
Return -1 if the value on the right is greater

The rules used by the combined comparison operator are same as the currently used comparison operators by PHP viz. <, <=, ==, >= and >. Those who are from PERL or RUBY programming background may already be familiar with this new operator proposed for PHP7.

   //Comparing Integers

    echo 1 <=> 1; //ouputs 0
    echo 3 <=> 4; //outputs -1
    echo 4 <=> 3; //outputs 1

    //String Comparison

    echo "x" <=> "x"; // 0
    echo "x" <=> "y"; //-1
    echo "y" <=> "x"; //1