Home >Backend Development >PHP Tutorial >How Does PHP's Conditional Operator (?:) Work?

How Does PHP's Conditional Operator (?:) Work?

Barbara Streisand
Barbara StreisandOriginal
2025-01-03 05:55:41538browse

How Does PHP's Conditional Operator (?:) Work?

The Conditional Operators of PHP: "?" and ":**"

In PHP, the "?" and ":" operators, collectively known as the conditional operator, allow you to evaluate a condition and conditionally assign a value to a variable.

Syntax:

$x ? $y : $z

Meaning:

This expression evaluates to $y if $x is true; otherwise, it evaluates to $z.

Example:

($request_type == 'SSL') ? HTTPS_SERVER : HTTP_SERVER

This expression returns the value of HTTPS_SERVER if $request_type is equal to 'SSL', otherwise it returns the value of HTTP_SERVER.

Short Form:

For convenience, PHP provides a short form of the conditional operator:

$x ?: $z

This expression is equivalent to:

$x ? $x : $z

It evaluates to $x if $x is true, otherwise it evaluates to $z.

Note:

It's important to note that the conditional operator is not specifically called "the ternary operator." While it is a ternary operator due to its three operands, many languages have multiple ternary operators.

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