Spaceship operator in PHP
After two years working in PHP/Laravel I got to know about the spaceship operator. The name sounds fancy as the operator performs.
In PHP, the “<=>” operator is referred to as the “spaceship operator” or “three-way comparison operator.” It was first used in PHP 7 to compare two expressions and return a value based on their relationship.
Suppose there is a code like this.
<?php
$a = 10;
$b = 5;
if ($a > $b) {
$result = 1;
} elseif ($a < $b) {
$result = -1;
} else {
$result = 0;
}
echo $result;
?>
Here we have to use multiple if else conditions however using “<=>” spaceship operator we can achieve that within one line.
The syntax of the spaceship operator is
var1 <=> var2
The result of the comparison will be:
- -1 if var1 is less than var2,
- 0 if var1 is equal to var2
- 1 if var1 is greater than var2.
The spaceship operator is particularly useful when sorting arrays or for comparing two values without the need for multiple conditional statements. It simplifies the code and makes it more concise.
<?php
$a = 10;
$b = 5;
$result = $a <=> $b;
echo $result
?>
In this example, $result will be 1 because $a is greater than $b.
Easy right !!