0
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. https://code.sololearn.com/wITmb1MSfr5R/?ref=app This might help to view quiz question screenshot: https://code.sololearn.com/W5KXX66aA0J9/?ref=app
4 Answers
+ 4
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:
https://www.php.net/manual/en/migration74.deprecated.php
+ 2
<?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.
+ 1
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
0
thank you all for answering this. now i got it. thanx