DEV Community

Mariusz Malek
Mariusz Malek

Posted on

Difference between Elvis, and Null Coalescing Operators

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;
Enter fullscreen mode Exit fullscreen mode

This is equivalent to:

$var ? $var : false;
Enter fullscreen mode Exit fullscreen mode

and

if ($var) {
    $result = $var;
} else {
    $result = false;
}
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

This is equivalent to:

isset($var) ? $var : false;
Enter fullscreen mode Exit fullscreen mode

and

if (isset($var)) {
    $result = $var;
} else {
    $result = false;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)