Spaceship, Ternary and Null Coalescing operators in PHP: Quick examples
Marcos Rezende
Posted on August 14, 2021
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);
Is the same of:
if ($expr1 < $expr2) {
$result = -1;
} else if ($expr1 == $expr2) {
$result = 0;
} else if ($expr1 > $expr2) {
$result = 1;
}
Ternary Operator
This:
$result = ($expr1) ? ($expr2) : ($expr3);
Is the same of:
if (true == $expr1) {
$result = $expr2;
} else {
$result = $expr3;
}
And this:
$result = ($expr1) ?: ($expr3);
Is the same of:
if (true == $expr1) {
$result = $expr1;
} else {
$result = $expr3;
}
Null Coalescing Operator
This:
$result = ($expr1) ?? ($expr3);
Is the same of:
if (null !== $expr1) {
$result = $expr1;
} else {
$result = $expr3;
}
You can play with here: https://3v4l.org/SWfOt
💖 💪 🙅 🚩
Marcos Rezende
Posted on August 14, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.