DEV Community

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

Posted on

1

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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)