DEV Community

Cover image for Spaceship, Ternary and Null Coalescing operators in PHP: Quick examples
Marcos Rezende
Marcos Rezende

Posted on

Spaceship, Ternary and Null Coalescing operators in PHP: Quick examples

These are so simple concepts, but sometimes forgotten by PHP developers. In order to quick introduce and explain how to use there three types of comparison operators in PHP, I've decided to share the simple codes bellow.

If you need further information, please check the official Comparison Operators documentation page.

Spaceship Operator

This:

$result = ($expr1) <=> ($expr2);
Enter fullscreen mode Exit fullscreen mode

Is the same of:

if ($expr1 < $expr2) {
    $result = -1;
} else if ($expr1 == $expr2) {
    $result = 0;
} else if ($expr1 > $expr2) {
    $result = 1;
}
Enter fullscreen mode Exit fullscreen mode

Ternary Operator

This:

$result = ($expr1) ? ($expr2) : ($expr3); 
Enter fullscreen mode Exit fullscreen mode

Is the same of:

if (true == $expr1) {
  $result = $expr2;
} else {
  $result = $expr3;
}
Enter fullscreen mode Exit fullscreen mode

And this:

$result = ($expr1) ?: ($expr3);
Enter fullscreen mode Exit fullscreen mode

Is the same of:

if (true == $expr1) {
  $result = $expr1;
} else {
  $result = $expr3;
}
Enter fullscreen mode Exit fullscreen mode

Null Coalescing Operator

This:

$result = ($expr1) ?? ($expr3);
Enter fullscreen mode Exit fullscreen mode

Is the same of:

if (null !== $expr1) {
  $result = $expr1;
} else {
  $result = $expr3;
}
Enter fullscreen mode Exit fullscreen mode

You can play with here: https://3v4l.org/SWfOt

Top comments (0)