How to Use Spaceship Operator in PHP

From WikiHTP

PHP 7 introduces a new kind of operator, which can be used to compare expressions. This operator will return -1, 0 or 1 if the first expression is less than, equal to, or greater than the second expression.

// Integers
print (1 <=> 1); // 0
print (1 <=> 2); // -1
print (2 <=> 1); // 1

// Floats
print (1.5 <=> 1.5); // 0
print (1.5 <=> 2.5); // -1
print (2.5 <=> 1.5); // 1
 
// Strings
print ("a" <=> "a"); // 0
print ("a" <=> "b"); // -1
print ("b" <=> "a"); // 1

Objects are not comparable, and so doing so will result in undefined behaviour.

This operator is particularly useful when writing a user-defined comparison function using usort, uasort, or uksort. Given an array of objects to be sorted by their weight property, for example, an anonymous function can use <=> to return the value expected by the sorting functions.

usort($list, function($a, $b) { return $a->weight <=> $b->weight; });

In PHP 5 this would have required a rather more elaborate expression.

usort($list, function($a, $b) {
    return $a->weight < $b->weight ? -1 : ($a->weight == $b->weight ? 0 : 1);
});

Realated[edit]

About This Tutorial

This page was last edited on 28 January 2019, at 07:37.