PHP 7 | Spaceship Operator


This article will make you aware of a very useful operator i.e the spaceship operator PHP 7. The spaceship operator or combined comparison operator is denoted by “<=>“. This is a three-way comparison operator and it can perform greater than, less than and equal comparison between two operands.
This operator has similar behavior like strcmp() or version_compare(). This operator can be used with integers, floats, strings, arrays, objects, etc.
This <=> operator offers combined comparison :

  • 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

Example:

 // Comparing Integers

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

// String Comparison

echo "a" <=> "a"; // outputs 0 
echo "m" <=> "y"; // outputs -1
echo "y" <=> "c"; // outputs 1
filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
echo"Integers \n";
echo 7 <=> 7 ;
echo"\n";
echo 7 <=> 6;
echo"\n";
echo 6 <=> 7;
  
echo"\nFloat\n";
  
echo 2.5 <=> 1.5; 
echo"\n";
echo 0.5 <=> 1.5; 
echo"\n";
echo 1.5 <=> 1.5; 
  
echo"\nStrings\n";
echo "a" <=> "a" ;
echo"\n";
echo "g" <=> "b"
echo"\n";
echo "a" <=> "b"
  
echo"\nArrays\n";
echo [] <=> []; 
echo"\n";
echo [1, 7, 3] <=> [1, 7, 3];
echo"\n";
echo [1, 7, 3, 5] <=> [1, 7, 3];
echo"\n";
echo [1, 7, 3] <=> [4, 4, 4];
echo"\n";
  
  
?>

chevron_right


Output:

Integers 
0
1
-1
Float
1
-1
0
Strings
0
1
-1
Arrays
0
0
1
-1

Reference:http://php.net/manual/en/language.operators.comparison.php



My Personal Notes arrow_drop_up

Sudipta sahana BTech 2nd year Cse student

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : nidhi_biet