What Does PHP's Elvis Operator (?:) Do and How Does It Work?

Mary-Kate Olsen
Release: 2024-11-13 12:19:02
Original
796 people have browsed it

What Does PHP's Elvis Operator (?:) Do and How Does It Work?

The Elvis Operator (?:) in PHP

The ?: operator, also known as the "Elvis operator," evaluates the left operand if it's truthy and the right operand otherwise. In short, it's a shortcut for the following:

foo = bar ? bar : baz;
Copy after login

Consider the code:

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

This code evaluates to $items if it's truthy (not empty or false), and evaluates to the $this->_handle->result('next', $this->_result, $this) expression otherwise.

Key Points:

  • The ?: operator is similar to the ternary operator, but the expression to evaluate to if the predicate is true is omitted.
  • foo ?: bar is equivalent to foo ? foo : bar.
  • The ?: operator ensures that the left operand is evaluated only once.
  • It can be used for "self-checking" of values, as seen in foo = foo ?: bar.
  • The Elvis operator's name refers to its resemblance to Elvis Presley's iconic hairstyle.

The above is the detailed content of What Does PHP's Elvis Operator (?:) Do and How Does It Work?. 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