<?php echo true?'what':true?'will':'print?';?>
Above code outputs will
.
I am not able to get logic behind it. Can anyone explain it.
Thanks in advance.
<?php echo true?'what':true?'will':'print?';?>
Above code outputs will
.
I am not able to get logic behind it. Can anyone explain it.
Thanks in advance.
You should work with braces:
echo true?'what':(true?'will':'print?');
this will output what
. The second if overrides the first if if there are no braces. Because ternary expressions get interpreted from left to right. So without any braces set by you PHPs interpreter will interpret your statement as:
echo (true?'what':true)?'will':'print?';
According to PHP.net you should avoid stacking ternary expressions:
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:
From documentation:
Note:
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:
Example #4 Non-obvious Ternary Behaviour
// however, the actual output of the above is 't' // this is because ternary expressions are evaluated from left to right
// the following is a more obvious version of the same code as above echo ((true ? 'true' : false) ? 't' : 'f');
// here, you can see that the first expression is evaluated to 'true', which // in turn evaluates to (bool)true, thus returning the true branch of the // second ternary expression.
The ternary operator in PHP is left-associative. Your code evaluates like this:
echo (true ? 'what' : true) ? 'will' : 'print?';
This is equivalent to:
echo (true) ? 'will' : 'print?';
And thus, the result is 'will'. You should use the following:
echo true ? 'what' : (true ? 'will' : 'print?');
A related post can be found here: Why is the output of `echo true ? 'a' : true ? 'b' : 'c';` 'b'?
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: (as given in document)
Example:
`
on first glance, the following appears to output 'true'
echo (true?'true':false?'t':'f');
however, the actual output of the above is 't'
this is because ternary expressions are evaluated from left to right
the following is a more obvious version of the same code as above
echo ((true ? 'true' : false) ? 't' : 'f');
here, you can see that the first expression is evaluated to 'true', which
in turn evaluates to (bool)true, thus returning the true branch of the
second ternary expression.
`