The ternary (?:
) operator is a conditional operator that allows to shorten if
/else
structures and decrease the length of code. The syntax for ternary operator can be represented as follows:
condition ? expression1 : expression2
condition
- is an expression that evaluates to a boolean value (true
orfalse
).expression1
- is an expression that will be evaluated ifcondition
istrue
.expression2
- is an expression that will be evaluated ifcondition
isfalse
.
Let's say we have if
/else
structure like this:
<?php
$number = 10;
if ($number % 2 === 0) {
$result = 'Even';
} else {
$result = 'Odd';
}
This code snippet can be rewritten as follows:
<?php
$number = 10;
$result = $number % 2 === 0 ? 'Even' : 'Odd';
PHP allows using nested ternary operators. These operators are left-associative instead of right-associative. It can be very confusing. So, in PHP 7.4 using nested ternary operators without explicit parentheses emits a deprecation warning.
Let's say we have the following code snippet:
<?php
$number = 10;
echo $number > 0 ? 'Positive' : $number < 0 ? 'Negative' : 'Zero';
In PHP 7.4 we will get a deprecation warning and the code prints Negative
instead of Positive
because ternary operator is left-associative:
Deprecated: Unparenthesized `a ? b : c ? d : e` is deprecated. Use either `(a ? b : c) ? d : e` or `a ? b : (c ? d : e)` in main.php on line 4
Negative
Since PHP 8.0, the nested ternary operators require explicit parentheses and using without them, a fatal error occurs.
If we run the previous code snippet in PHP 8.0 or newer versions, we will get a fatal error:
Fatal error: Unparenthesized `a ? b : c ? d : e` is not supported. Use either `(a ? b : c) ? d : e` or `a ? b : (c ? d : e)` in main.php on line 4
Code snippet can be rewritten as follows:
<?php
$number = 10;
echo $number > 0 ? 'Positive' : ($number < 0 ? 'Negative' : 'Zero');
Output:
Positive
Leave a Comment
Cancel reply