+ 5
Hi friends. Why does this code output 2 ??? I didn't understand?
<?php $var = true ? '1' : false ? '2' : '3'; echo $var; ?> https://code.sololearn.com/wMd7Sx3SbsFu/?ref=app
4 Respuestas
+ 3
Ipang , I agree with the rest, but I don't think the assignment operator gets precedence here. It's more like
$var = (((true) ? '1' : false) ? '2' : '3');
$var = (('1') ? '2' : '3');
$var = ((true) ? '2' : '3'); // '1' is true
$var = ('2');
$var = '2';
I probably should have elaborated my first comment further.
Edit: Ipang seems to have deleted his comment.
+ 5
Strange indeed! The ternary operator appears to be left-associative in PHP, so the expression is evaluated as
$var = (true ? '1' : false) ? '2' : '3';
First the stuff in parentheses is evaluated as true, which in turn makes '2' the final value of the expression. We can fix this by using parentheses differently
$var = true ? '1' : (false ? '2' : '3');
+ 5
Okay, I found this in the docs, with an almost identical code: 'It is recommended that you avoid "stacking" ternary expressions. PHP's behaviour when using more than one ternary operator within a single statement is non-obvious'.
Please read further here (second Note in the Ternary Operator section):
http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary
+ 1
Ipang You're welcome! Your explanation was much clearer and hence quite helpful 😊👍
Edit: Ipang has deleted his comment, but he helped me clarify my first comment.