Home  >  Article  >  Backend Development  >  What is the Elvis Operator (?:) and How Does it Work in PHP?

What is the Elvis Operator (?:) and How Does it Work in PHP?

Linda Hamilton
Linda HamiltonOriginal
2024-11-13 16:13:02349browse

What is the Elvis Operator (?:) and How Does it Work in PHP?

Elvis Operator (?:) Unraveled in PHP

In the depths of a complex PHP codebase, you may encounter a mysterious operator: the ?: operator. Dubbed the "Elvis operator," it may have you wondering, "What's its purpose?"

The ?: operator, in essence, evaluates to its left operand if the left operand is considered "truthy," and the right operand otherwise. In other words:

foo ?: bar

is roughly equivalent to the ternary operator:

foo ? foo : bar

or in a traditional if-else statement:

if (foo) {
    foo = foo;
} else {
    foo = bar;
}

However, unlike the ternary operator, the ?: operator evaluates the left operand only once, enhancing efficiency.

Example Usage

One common use case is for self-checking, as seen in the code snippet:

$items = $items ?: $this->_handle->result('next', $this->_result, $this);

Here, it assigns the result of $this->_handle->result() to $items if $items is null or falsey, while leaving $items unchanged otherwise.

Additional Examples

Here are a few more examples to illuminate the behavior:

var_dump(5 ?: 0); // 5
var_dump(false ?: 0); // 0
var_dump(null ?: 'foo'); // 'foo'
var_dump(true ?: 123); // true
var_dump('rock' ?: 'roll'); // 'rock'
var_dump('' ?: 'roll'); // 'roll'
var_dump('0' ?: 'roll'); // 'roll'
var_dump('42' ?: 'roll'); // '42'

Should you encounter a ?: operator in the future, remember that its goal is to provide a concise way to evaluate and assign based on truthiness, making your code more efficient and readable.

The above is the detailed content of What is the Elvis Operator (?:) and How Does it Work in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn