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;
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';
If 'user' exists but is an empty string or 0, PHP assigns 'guest'.
Example with Null Coalescing:
$username = $_GET['user'] ?? 'guest';
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';
If $name is not truthy, this shows 'Anonymous'.
Shorten Repeated Conditions
$result = $data['value'] ?: 'N/A';
Without Elvis:
$result = $data['value'] ? $data['value'] : 'N/A';
This double reference disappears with ?:.
In Return Statements
return $config['path'] ?: '/default/path';
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)