PHP Spaceship Operator

The PHP spaceship operator is a new operator introduced in PHP 7.

How does look the Spaceship Operator?

<=> – PHP Spaceship Operator.

<?php
$a = 15;
$b = 70;

echo $a <=> $b;
?>

How does it work?

It returns -1 or 0 or 1.

$a = 15;
$b = 70;

  • If $a is less than $b it will return -1.
  • It will return 0 if $a is equal to $b.
  • and at the last, it will return 1 if $a is greater than $b.

Example:

<?php
echo 15 <=> 70;

echo "<br>";

echo 22 <=> 22;

echo "<br>";

echo 70 <=> 15;
?>
Browser Output
-1
0
1

In the following example, you can see how you use the spaceship operator with conditional statements.

<?php
$a = 70;
$b = 65;

if(($a <=> $b) === -1){
    echo '$a is less than $b';
}
elseif($a <=> $b){
    echo '$a is greater than $b';
}
else{
    echo '$a is equal to $b';
}
?>
Browser Output
$a is greater than $b

Leave a Reply

Your email address will not be published. Required fields are marked *