Comparing two values is a frequent operation in any programming language. We use various language operators to express the type of comparison we wish to execute between two variables. In PHP, these operators include equal ($a == $b
), identical ($a === $b
), not equal ($a != $b
or $a <> $b
), not identical ($a !== $b
), less than ($a < $b
), greater than ($a > $b
), less than or equal to ($a <= $b
), and greater than or equal to ($a >= $b
) comparisons.
All of these comparison operators result in Boolean true
or false
. Sometimes, however, there are cases where a three-way comparison is needed, in which case, the result of the comparison is more than just a Boolean true
or false
. While we can achieve a three-way comparison using various operators through various expressions, the solution is all but elegant.
With the release of PHP 7, a new spaceship <=>
operator has been introduced, with a syntax as follows:
(expr) <=> (expr)
The spaceship <=>
operator offers combined comparison. After comparison, it follows these conditions:
- It returns
0
if both operands are equal - It returns
1
if the left operand is greater - It returns
-1
if the right operand is greater
Comparison rules used to yield the preceding results are the same as those used by existing comparison operators: <
, <=
, ==
, >=
, and >
.
The usefulness of the new operator is especially apparent with ordering functions. Without it, the ordering functions were quite robust, as per the following example:
$users = ['branko', 'ivana', 'luka', 'ivano']; usort($users, function ($a, $b) { return ($a < $b) ? -1 : (($a > $b) ? 1 : 0); });
We can shorten the preceding example by applying the new operator to it, as follows:
$users = ['branko', 'ivana', 'luka', 'ivano']; usort($users, function ($a, $b) { return $a <=> $b; });
Applying the spaceship <=>
operator, where applicable, gives the expressions simplicity and elegance.