The Elvis operator is a variant of the conditional operator with no expression between `?` and `:`. exp1 ?: exp2 is equivalent to exp1 ? exp1 : exp2.
The Elvis operator is a variation of the conditional (AKA ternary) operator that can be used when the value to be returned is the same as the condition expression when it's truthy. It's written using the same ?:
notation, except the expression between ?
and :
is omitted.
Thus,
condition ?: expression
is equivalent to
condition ? condition : expression
except that condition
will only be evaluated once.
In some programming languages the short-circuiting ||
operator serves this purpose. But in PHP, ||
always converts its result to a boolean, while the elvis operator returns the actual value of the selected operand.