Condition operator in php | SoloLearn: Learn to code for FREE!


Condition operator in php

i got this ques in quiz.. and answer was 2.. can anyone explain how? any help will be appriciated... thanx in advance. This might help to view quiz question screenshot:


7/26/2020 6:19:52 PM

Vahida Vadiya

4 Answers

New Answer


this is because PHP ternary expressions are left-associative (unlike all other languages, where it's right-associative), such that your code is actually equivalent to this: $var = ( true ? '1': false ) ? '2':'3'; here, you can see that the first expression is evaluated to '1', which in turn evaluates to (bool)true, thus returning the true branch of the second ternary expression ('2'). furthermore, as PHP 7.4, the use of chained ternaries without brackets is deprecated:


<?php $var =(true ? '1': (false ? '2':'3')); echo $var; ?> I think, answer is 1. Only.. If it like <?php $var =(!true ? '1': (!false ? '2':'3')); echo $var; ?> then only 2.. Edit : Vahida Vadiya But compiler showing error without brackets and warning as deprecated. So since this old question, it may updated rules for brackets. So am assuming before it is same as this way as default <?php $var =(true ? '1': false )? '2':'3'; echo $var; ?> This prints 2.


codemonkey , Vahida Vadiya as it showing deprecated warning, so am assuming defultly this before update.. Since question is old one... But am not sure, not much know about php... like this .. It result 2.. <?php $var =(true ? '1': false )? '2':'3'; echo $var; ?> 2


thank you all for answering this. now i got it. thanx