Wednesday, October 24, 2018

What is (the 'Spaceship' Operator) in PHP 7?

According to the RFC that introduced the operator, $a <=> $b evaluates to:




  • 0 if $a == $b

  • -1 if $a < $b

  • 1 if $a > $b




which seems to be the case in practice in every scenario I've tried, although strictly the official docs only offer the slightly weaker guarantee that $a <=> $b will return




an integer less than, equal to, or greater than zero when $a is respectively less than, equal to, or greater than $b




Regardless, why would you want such an operator? Again, the RFC addresses this - it's pretty much entirely to make it more convenient to write comparison functions for usort (and the similar uasort and uksort).



usort takes an array to sort as its first argument, and a user-defined comparison function as its second argument. It uses that comparison function to determine which of a pair of elements from the array is greater. The comparison function needs to return:





an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.




The spaceship operator makes this succinct and convenient:



$things = [
[
'foo' => 5.5,
'bar' => 'abc'

],
[
'foo' => 7.7,
'bar' => 'xyz'
],
[
'foo' => 2.2,
'bar' => 'efg'
]
];


// Sort $things by 'foo' property, ascending
usort($things, function ($a, $b) {
return $a['foo'] <=> $b['foo'];
});

// Sort $things by 'bar' property, descending
usort($things, function ($a, $b) {
return $b['bar'] <=> $a['bar'];
});



More examples of comparison functions written using the spaceship operator can be found in the Usefulness section of the RFC.

No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...