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
<?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"; ?> |
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
Recommended Posts:
- Ternary operator vs Null coalescing operator in PHP
- 'AND' vs '&&' as operator in PHP
- PHP | $ vs $$ operator
- What is the !! (not not) operator in JavaScript?
- Double not (!!) operator in PHP
- What is the difference between the | and || or operator in php?
- Instanceof operator in JavaScript
- Arrow operator in ES6 of JavaScript
- Difference between != and !== operator in JavaScript
- JavaScript | typeof operator
- How to get negative result using modulo operator in JavaScript ?
- Ternary operator / Question mark and colon in JavaScript
- JavaScript Course | Conditional Operator in JavaScript
- How to insert HTML content into an iFrame using jQuery?
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



