What Is the Elvis Operator?
The Elvis operator is a shorthand for a simple if-else
expression. PHP does not have a native Elvis operator, but you can simulate it using the ternary operator without the middle part.
$username = $input['name'] ?: 'Guest';
This checks if $input['name']
is truthy. If yes, it assigns it to $username
. If not, it sets 'Guest'
as default.
Syntax and Behavior
You can write ternary syntax like this:
$result = $condition ? $trueValue : $falseValue;
Elvis-style syntax removes the middle part:
$result = $value ?: $default;
- It checks if
$value
is truthy - If true, it returns
$value
- If false, it returns
$default
When to Use It
Use the Elvis-style operator when:
- You need to provide a default value
- You want to simplify a long
if
block - You handle user input or optional data
Example:
$email = $_POST['email'] ?: 'no-reply@example.com';
If the user gives an email, it uses it. If not, it falls back to 'no-reply@example.com'
.
Important Notes
PHP treats these as falsy values:
false
null
0
-
''
(empty string) '0'
Example:
$number = 0;
$result = $number ?: 100; // Returns 100, not 0
This can cause bugs if 0
is valid. To avoid this, use isset()
or the null coalescing operator.
Comparison with Null Coalescing
Use the null coalescing operator (??
) when you want to check only null.
$name = $input['name'] ?? 'Unknown';
-
??
checks fornull
only -
?:
checks for all falsy values
Choose based on what counts as "missing" in your logic.
Summary
- PHP simulates the Elvis operator using
?:
- It helps assign fallback values quickly
- Be careful with values like
0
or empty strings - Use
??
if you only want to check fornull
The Elvis pattern saves time and makes code shorter—but it needs thoughtful use.
Source: flatcoding.com
Top comments (2)
What do you think a native Elvis operator is?
The Elvis operator is nothing more than a shorthand ternary operator.
I never used it in codebases because the behaviour can cause errors. The same reason I avoid empty.
Good, very interesting!
If it could be of interest to someone who maybe wants to enter the world of PHP, i also created an online php course, you can find it here chiccohunt.gumroad.com/l/fhzvh
Some comments may only be visible to logged-in visitors. Sign in to view all comments.