Combined comparison Operator (<=>) and null coalescing operator (??)

509 views Asked by At

Details about combined comparison operator (<=>) and null coalescing operator (??)

1

There are 1 answers

2
dave On BEST ANSWER

The combined comparison operator return -1, 0, or 1, depending on which is greater than the other:

if ($x <=> $y == -1) {
    echo '$x < $y';
} elseif ($x <=> $y == 1) {
    echo '$x > $y';
} else {
    echo '$x == $y';
}

The null coalescing operator is similar to doing $x ?: $y, but is checking for null instead of false-y:

$x = null;
$y = 'hello';
echo $x ?? $y; //hello
echo $x ?: $y; //hello
$x = 0;
$y = 1;
echo $x ?? $y; //0;
echo $x ?: $y; //1