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

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

Barbara Streisand
Release: 2025-01-03 05:55:41
Original
533 people have browsed it

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

Meaning:

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

Example:

($request_type == 'SSL') ? HTTPS_SERVER : HTTP_SERVER
Copy after login

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

This expression is equivalent to:

$x ? $x : $z
Copy after login

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!

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