Home > Backend Development > PHP Tutorial > 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
Release: 2024-11-13 16:13:02
Original
405 people have browsed it

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
Copy after login

is roughly equivalent to the ternary operator:

foo ? foo : bar
Copy after login

or in a traditional if-else statement:

if (foo) {
    foo = foo;
} else {
    foo = bar;
}
Copy after login

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);
Copy after login

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'
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template