0

I understand how the operator works.

It compresses this:

if ($a > $b) {
    return 1;
} else if ($a < b) {
    return -1;
} else {
    return 0;
}

into this

$a <=> $b

But where and how will I use it?

The only place this is somewhat useful is on the callback of usort. Except there, to use the returned value I still have to use switch and that defeats the purpose.

switch ($a <=> $b) {
    case -1: //code
    case 0:  //code
    case 1:  //code
}

Update: My question is not how to use it or how it works. I am asking where this is useful.

Mihai Răducanu
  • 9,553
  • 4
  • 19
  • 28
  • 1
    Even if you *just* use it for `usort`, isn't that pretty good already? That's an obvious use case. I'm sure you'll discover other potential use cases over time. You can have this kind of discussion about pretty much any keyword/operator: there are always other ways to write the same thing. – deceze Feb 19 '16 at 12:56
  • 1
    The [main purpose](https://wiki.php.net/rfc/combined-comparison-operator#usefulness) of this operator introduced on PHP 7 is to simplify the writing of callback comparison functions for [`usort()`](http://php.net/manual/en/function.usort.php) and similar. – axiac Feb 19 '16 at 12:58
  • "How to use it" and "where is it useful" are virtually the same question! You use it when you want to compare two values and need a return value of <0, 0 or >0. Beyond this it's purely opinion based in which specific code situations you can use this to solve a problem. – deceze Feb 19 '16 at 13:10
  • Let me rephrase: where would I need this operator except in the usort function? Give me an example of where you used it. – Mihai Răducanu Feb 19 '16 at 13:17
  • 1
    Stack Overflow is not for polling for random examples. – No, I cannot currently think of an example other than `usort` off the top of my head. But I'll keep this in the back of my mind should I ever encounter a situation where it *is* useful. – deceze Feb 19 '16 at 13:19

0 Answers0