PHP 7 and the spaceship operator

Besides new features like type hinting for scalar datatypes or the optimized performance, PHP 7 also brings many new, useful language extensions, and finally the "spaceship operator" has made it into the world of PHP (Ruby and Perl programmers have known it for a long time). \($a <=> $b\) returns \(0\) if both operands are equal, \(1\) if the left one is larger and \(-1\) otherwise .


Therefore, this new operator corresponds to the signum function \(sgn(x-y)\) known from mathematics, so that already existing comparison operators can also be interpreted with the help of the new syntax:

\($a < $b\) \(($a <=> $b) === -1\)
\($a <= $b\) \(($a <=> $b)\) !\(== 1\)
\($a == $b\) \(($a <=> $b) === 0\)
\($a\) !\(= $b\) \(($a <=> $b)\) !\(== 0\)
\($a >= $b\) \(($a <=> $b)\) !\(== -1\)
\($a > $b\) \(($a <=> $b) === 1\)

Thus the same rules apply as for the comparison operators (e.g. \([1,2,3] <=>[1,2,1]\) is equal to \(1\)) .

Back