What Is the Elvis Operator in PHP?

In PHP 5.3, a shorter syntax for the ternary operator was introduced, which allows to leave out the middle part of the ternary operator for a quick shorthand evaluation. It has the following syntax:

// PHP 5.3+
expr1 ?: expr2;

This shorthand syntax is also referred to as the elvis operator (?:). Note that all of the following statements are equivalent:

// using the elvis operator
expr1 ?: expr2;
// using the ternary operator
expr1 ? expr1 : expr2;
// using if/else
if (expr1) {
    return expr1;
} else {
    return expr2;
}

The statements above translate to; if expr1 evaluates to true, return expr1, otherwise return expr2. This means that, if a falsy value is encountered, the elvis operator will return the second operand, and if a truthy value is encountered, the first operand (i.e. the truthy value) will be returned.

Note that when the left hand side of the elvis operator evaluates to true, the right hand side of the expression is not evaluated. This is because of short-circuiting — which means the second operand is executed / evaluated only if the first operand does not evaluate to true.

Ternary Chaining

One useful feature of the elvis operator is that you can use it to chain ternaries, for example, like so:

echo 0 ?: 1 ?: 2 ?: 3; // output: 1

In such a case first truthy value it encounters is returned. This is the same as writing a series of if / elseif / else statements, for example, like so:

if (expr1) {
    return expr1;
} else if (expr2) {
    return expr2;
} else if (expr3) {
    return expr3;
} else {
    return expr4;
}

Similarities With Other Languages

In certain programming languages (such as Perl, Python, Ruby, and JavaScript), the elvis operator is written as the OR operator (typically || or or). This has the same behavior, i.e. returning its first operand if it evaluates to true, or evaluating and returning its second operand otherwise.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.