PHP Shorthand Ternary Elvis Operator Explained
This article explains the shorthand ternary operator, commonly known
as the Elvis operator (?:), in PHP. You will learn its
syntax, how it differs from the standard ternary operator, when to use
it, and how it compares to the null coalescing operator
(??) to help you write cleaner and more concise PHP
code.
In PHP, the standard ternary operator is used as a shortcut for
if-else statements. Its syntax is:
$result = $condition ? $value_if_true : $value_if_false;
The shorthand ternary operator, or Elvis operator (?:),
is a variation of this that omits the middle part. Its syntax is:
$result = $expression1 ?: $expression2;
This expression evaluates to $expression1 if
$expression1 evaluates to true (or is truthy).
If $expression1 evaluates to false (or is
falsy, such as 0, empty string,
null, or an empty array), it returns
$expression2.
The nickname “Elvis operator” comes from the fact that when viewed
sideways, the ?: characters resemble an emoticon of Elvis
Presley with his signature hairstyle.
Here is a practical example of how the Elvis operator simplifies your code:
// Traditional ternary operator
$username = $_POST['username'] ? $_POST['username'] : 'anonymous';
// Shorthand ternary (Elvis) operator
$username = $_POST['username'] ?: 'anonymous';In the shorthand version, PHP evaluates
$_POST['username']. If it contains a truthy value, that
value is assigned to $username. If it is empty or false,
the string 'anonymous' is assigned instead. This prevents
you from having to write the same variable or expression twice.
It is important to distinguish the Elvis operator (?:)
from the Null Coalescing operator (??) introduced in PHP
7.
The Elvis operator (?:) checks for truthiness. However,
if the variable on the left is undefined, it will trigger an “Undefined
variable” or “Undefined array key” notice.
The Null Coalescing operator (??) specifically checks if
a variable exists and is not null. It does not trigger any
notices if the variable is undefined. Furthermore, the null coalescing
operator treats empty strings ("") and 0 as
valid values, whereas the Elvis operator treats them as falsy and will
fall back to the default value.