Difference between Elvis, and Null Coalescing Operators
Mariusz Malek
Posted on October 7, 2022
In this article, I will show you the differences between popular operators in PHP. I hope my short post will help you understand operators better.
Elvis operator
The elvis operator (?:) is actually the name used for the abbreviated ternary operator (which was introduced in PHP 5.3). The elvis operator is a shorthand operator for the ternary operator. We can also say that it is a modified form of the ternary operator. To understand the Elvis operator in PHP, we need to know the ternary operator and how it works. The ternary operator is a conditional operator used to perform a simple comparison or check of a condition having simple statements. It is a shorter version of the if-else statement.
It has the following syntax:
$var ?: false;
This is equivalent to:
$var ? $var : false;
and
if ($var) {
$result = $var;
} else {
$result = false;
}
Null Coalescing Operator
The null coalescing operator (??) was introduced in PHP 7. The null coalescing operator checks whether the specified variable is null or not, and returns a non-null value from the value pair. The output of the null coalescing operator depends on whether the variable is null.
It has the following syntax:
$var ?? false;
This is equivalent to:
isset($var) ? $var : false;
and
if (isset($var)) {
$result = $var;
} else {
$result = false;
}
Posted on October 7, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
September 10, 2024