According to this, the spaceship operator (<=>) returns "an integer less than, equal to, or greater than zero, depending on if $x is less than, equal to, or greater than $y".
Trying it out, it seems to only return -1, 0, or 1.
Is that always the case?
CodePudding user response:
From PHP's New feature's page:
Spaceship operator
The spaceship operator is used for comparing two expressions.
It returns-1
,0
or1
when$a
is respectively less than, equal to, or greater than$b
.
Comparisons are performed according to PHP's usual type comparison rules.
So, only -1
, 0
or 1
can be returned from <=>
CodePudding user response:
The current implementation always returns those values for normal inputs. When it compares two numbers, it normalises the result using this macro:
#define ZEND_NORMALIZE_BOOL(n) \
((n) ? (((n)<0) ? -1 : 1) : 0)
(It does have provision for objects provided by extensions to have their own implementation, though, so those could return a different value.)
However, the official documentation only guarantees "an int less than, equal to, or greater than zero". Its intended usage is in functions such as usort which look for those values.
Since this is a common convention, if you're writing your own code, it's probably better to stick to that than explicitly check for -1 and 1.
That's less likely to cause surprises down the road if the implementation changes, or you need to interact with a different source of comparisons.