The Elvis operator in PHP is a shorthand version of the ternary operator. PHP allows developers to use this conditional operator to reduce code length and simplify logic where a default value is needed.
Table of Content
It gets its name because the symbol ?:
resembles an emoticon of Elvis Presley’s hair. The operator helps when you want to check a condition and return a fallback value without repeating the same expression.
Understand PHP Elvis Operator?
The Elvis operator is a simplified ternary expression. You use it when the condition and the result share the same value.
Instead of writing the same variable twice, the Elvis operator checks it once and returns it if it is truthy. If not, it returns the fallback value.
Here is the syntax:
$variable = $value ?: $default;
This line means: if $value
is true (not null, false, 0, empty string, etc.), then assign $value
to $variable
. Otherwise, assign $default
to $variable
.
So, how does the Elvis operator work in PHP?
The Elvis operator is a conditional operator that checks the first operand. If PHP evaluates it as true, then it returns that operand. If PHP evaluates it as false, it returns the second operand. This behavior depends on PHP’s rules for truthy and falsy values.
Here are a few values PHP treats as false:
false
0
(integer)""
(empty string)null
[]
(empty array)
If $value
equals any of these, the Elvis operator moves to the fallback value. If $value
holds a valid non-empty value, it returns that.
Use the Elvis operator when you want to:
- Provide a default value
- Avoid writing the same variable twice
- Clean up ternary expressions with simple fallback logic
It is useful for configuration, templates, quick logic, or anywhere you want to avoid isset()
or empty()
calls.
The Difference Between Elvis Operator and Ternary Operator in PHP
The ternary operator in PHP uses this form:
$variable = $condition ? $trueResult : $falseResult;
You must always provide all three parts: the condition, the result if true, and the result if false. This structure gives you full control but adds repetition when the condition and true result are the same.
The Elvis operator is a shortcut:
$variable = $value ?: $fallback;
It skips the middle part. You do not need to repeat $value
. That saves space and reduces clutter. But it only works when the left-hand value is both the condition and the expected result.
Here are examples for each one:
Ternary:
$name = isset($_GET['name']) ? $_GET['name'] : 'Guest';
Elvis:
$name = $_GET['name'] ?: 'Guest';
You should note that the Elvis operator does not check if a variable exists. If $_GET['name']
is not set, you get a warning. The ternary operator, with isset()
, avoids that.
Use the Elvis operator only if the variable or expression already exists. If you need to check existence or type, use the full ternary or ??
(null coalescing) instead.
Elvis Operator vs Null Coalescing Operator
The null coalescing operator (??
) checks if the variable exists and is not null. It does not check if the value is empty or false. That makes it different from the Elvis operator.
Syntax:
$result = $value ?? $fallback;
- Elvis checks for truthy values.
- Null coalescing checks for
null
only.
For example:
$value = 0;
$result1 = $value ?: 'fallback'; // returns 'fallback'
$result2 = $value ?? 'fallback'; // returns 0
Here, $value
is zero. The Elvis operator treats zero as false, so it returns 'fallback'
. The null coalescing operator only checks for null, so it returns 0
.
In settings where zero, empty string, or false are valid values, avoid the Elvis operator. It will override those with the fallback. Use ??
to keep them.
Examples
Using Elvis Operator with Function Returns:
You can combine the Elvis operator with functions that may return empty or false values.
function getUsername($id) {
$users = [1 => 'Alice', 2 => 'Bob'];
return $users[$id] ?? '';
}
$username = getUsername(3) ?: 'Anonymous';
echo $username; // Output: Anonymous
The function returns an empty string when the ID is not found. The Elvis operator treats the empty string as false and switches to 'Anonymous'
.
If the ID exists:
$username = getUsername(2) ?: 'Anonymous';
echo $username; // Output: Bob
The Elvis operator keeps 'Bob'
since the value is not false.
Chaining Elvis Operators:
You can chain Elvis operators to test multiple fallback values.
$first = '';
$second = null;
$third = 'Final Value';
$result = $first ?: $second ?: $third;
echo $result; // Output: Final Value
PHP checks each value from left to right. It stops at the first truthy value.
If all are falsy:
$first = '';
$second = 0;
$third = false;
$result = $first ?: $second ?: $third ?: 'Nothing';
echo $result; // Output: Nothing
This helps when you want a backup value after testing several variables.
Wrapping Up
In this article, you learned a conditional operator which is an Elvis operator. You also saw the difference between the Elvis operator, the ternary operator, and the null coalescing operator.
Here is a quick recap:
- The Elvis operator
?:
returns the left-hand value if true, or a fallback if not. - It is a shortcut for simple ternary conditions.
- It only works when the same value is both the condition and the true result.
- It treats
false
,0
,null
, and empty values as false. - The null coalescing operator only checks for
null
, not false or empty. - Use the Elvis operator when you want quick, clean code and do not need to check variable existence.
FAQ’s
What is the Elvis operator in PHP?
How is the Elvis operator different from the ternary operator in PHP?
$value = $x ? $x : 'default';
The Elvis operator skips the middle part and works like this:
$value = $x ?: 'default';
It only works if the left side is both the condition and the result.
What is the difference between Elvis operator and null coalescing operator in PHP?
Can I use the Elvis operator with function returns?
$name = getUsername($id) ?: 'Guest';
If the function returns '' or null, it switches to 'Guest'.
Is Elvis operator faster than ternary or null coalescing?
Similar Reads
PHP and MySQL have become an inseparable pair for web developers. One handles the logic, while the other stores the…
You may need to repeat tasks in PHP. The PHP for loop solves this by letting you run code many…
The filter_var_array() appeared to make input validation simple and sanitization in PHP. It handles multiple inputs with different filters was…
There are some tools known as "PHP magic constants" that will make your code a little more clever and versatile.…
Keeping track of the last record inserted is often important. Whether you are managing user registrations, processing orders, or handling…
A PHP OOP constructor initializes an object when it is created. In this article, we will cover the following topics:…
PHP didn’t have a way to check or clean user input. Developers used scattered code—some wrote custom checks, others used…
PHP introduced traits to solve a problem with code reuse. Before traits, developers used inheritance and interfaces to share functionality…
PHP introduced null to handle undefined or missing values. It helps prevent errors when you check if a variable exists.…
The PHP continue statement skips the rest of the loop in the current cycle. It jumps to the next cycle…