CodeNewbie Community 🌱

Montasser
Montasser

Posted on

The PHP Elvis Operator (?:) Explained

The Elvis operator in PHP looks like this: ?:. It offers a short way to check a value and fall back to another one if the first is not usable. PHP introduces it in version 5.3.

What It Does

The PHP Elvis operator checks the value on the left. If that value is truthy, PHP uses it. If not, PHP returns the value on the right.

Basic Form:

$result = $a ?: $b;
Enter fullscreen mode Exit fullscreen mode

This means:
β€œIf $a is true, use $a. If not, use $b.”

This operator works with any expression. It does not check only if $a exists;

it checks if $a holds a truthy value. If $a is false, null, 0, '', or an empty array, PHP treats it as false and moves to $b.

How It Differs from ??

This is where confusion often starts. The null coalescing operator (??) also sets a fallback value. But it behaves differently.

Example with Elvis:

$username = $_GET['user'] ?: 'guest';
Enter fullscreen mode Exit fullscreen mode

If 'user' exists but is an empty string or 0, PHP assigns 'guest'.

Example with Null Coalescing:

$username = $_GET['user'] ?? 'guest';
Enter fullscreen mode Exit fullscreen mode

This one checks only if 'user' exists and is not null. If it’s an empty string or 0, it still assigns that value.

Use ?: when you want to check if a value actually holds something useful. Use ?? when you just care about presence.

Use Cases

Default Display Text

echo $name ?: 'Anonymous';
Enter fullscreen mode Exit fullscreen mode

If $name is not truthy, this shows 'Anonymous'.

Shorten Repeated Conditions

$result = $data['value'] ?: 'N/A';
Enter fullscreen mode Exit fullscreen mode

Without Elvis:

$result = $data['value'] ? $data['value'] : 'N/A';
Enter fullscreen mode Exit fullscreen mode

This double reference disappears with ?:.

In Return Statements

return $config['path'] ?: '/default/path';
Enter fullscreen mode Exit fullscreen mode

You avoid declaring a temporary variable.

Precautions

Falsy But Valid:
Values like 0, '0', and false fail the Elvis check. If these are valid in your context, don’t use ?:. Use ?? or a stricter condition.
Undefined Variables:
Elvis evaluates the left side first. If the variable is not defined, PHP throws a notice. ?? avoids that by checking if the variable exists first.
Readability:
Short code is not always better code. Use ?: only when the intent stays clear. If a developer has to pause to understand, you lose clarity.

Final Thoughts

The Elvis operator brings a cleaner way to set defaults, but it has limits. It trades explicit logic for shorter syntax. Use it when the check is simple and readability stays intact. If you need to allow values like 0 or empty strings, choose the null coalescing operator instead.

Thank you for reading. Visit FlatCoding Blog To see more PHP tutorials.

Top comments (0)