DEV Community

Mariusz Malek
Mariusz Malek

Posted on

6

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay