Home >Backend Development >PHP Tutorial >How Does PHP's Conditional Operator Work?
Exploring PHP's Conditional Operators
PHP offers several operators to handle conditional statements, with the "?:" and ":" operators serving as essential tools.
The Conditional Operator (? :)
The conditional operator "?" acts like an inline "if-else" statement. It takes the form:
$x ? $y : $z
This expression evaluates to $y if $x is true (i.e., not false, null, or 0) and to $z otherwise. For example:
($request_type == 'SSL') ? HTTPS_SERVER : HTTP_SERVER
This expression returns HTTPS_SERVER if $request_type is 'SSL' and HTTP_SERVER otherwise.
Short Form (? :)
PHP provides a short form for the conditional operator:
$x ?: $z
This form evaluates to $x if $x is true and to $z if $x is false.
Distinguishing Ternary Operator
While the conditional operator is commonly referred to as the "ternary operator," this designation is actually a misnomer. Ternary operators have three operands, and "?" is just one of many ternary operators in PHP.
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!