Home > Backend Development > PHP Tutorial > When and How to Use the Elvis Operator (?:) in PHP?

When and How to Use the Elvis Operator (?:) in PHP?

Linda Hamilton
Release: 2024-11-11 11:45:03
Original
867 people have browsed it

When and How to Use the Elvis Operator (?:) in PHP?

The Elvis Operator (?:) in PHP

In PHP, the ?: operator is known as the Elvis operator, a conditional expression that simplifies the common use case of assigning a default value to a variable if the original value is null or falsey.

Using the Elvis Operator

The Elvis operator evaluates to the left operand if the left operand is truthy (not null, not false, and not an empty string). Otherwise, it evaluates to the right operand.

Syntax

variable = expression_to_test ?: default_value;
Copy after login

Examples

  • Assign 'foo' to the variable 'bar' if it's null or falsey:

    $bar = $foo ?: 'foo';
    Copy after login
  • In the example you provided:

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

    This assigns the result of $this->_handle->result('next', $this->_result, $this) to $items if $items is null or falsey.

Advantages of the Elvis Operator

  • Code optimization: It eliminates the need for nested ternary operators or if-else statements.
  • Improved readability: It makes code more concise and easier to understand.

Elvis Operator vs. Ternary Operator

While the Elvis operator and ternary operator (?: :) both evaluate expressions based on conditions, there are key differences:

  • The Elvis operator only evaluates the left operand if the condition is true.
  • The ternary operator evaluates both the true and false expressions regardless of the condition.

The above is the detailed content of When and How to Use the Elvis Operator (?:) 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