<?php
$var = 4;
echo $current = ($var > 2) ? "gr than 2" : ($var > 6) ? "gr than 6" : "not gr than 2 or 6";
?>
for the above code, it always returns - gr than 6. Can someone please suggest what did I wrong?
<?php
$var = 4;
echo $current = ($var > 2) ? "gr than 2" : ($var > 6) ? "gr than 6" : "not gr than 2 or 6";
?>
for the above code, it always returns - gr than 6. Can someone please suggest what did I wrong?
The code will be executed front to back. So first
<?php
($var > 2) ? "gr than 2" : ($var > 6)
?>
will result in "gr than 2".
Then the next questionmark will result in gr than 6, because "gr than 2" is equal to true.
Also because of the above it would be good to notice that > 6 and > 2 are both greater than 2, so the whole line is actually quite pointless the way it is written.
The solution would be something like:
<?php
$var = 4;
echo $current = ($var < 2 ? "not gr than 2 or 6" : ($var > 6 ? "gr than 6" : "gr than 2"));
?>
* Edit: *
Thank you for the upvotes. When looking again at this I got lost in my own post, because the logic is so complex. So for others reading this:
The logic the OP posted can be simplified to the following:
<?php
echo true ? "first" : false ? "second" : "third";
The OP would expect this to result in first.
However, it does result in second because first the first part is being executed, and because that part is true the outcome is "second".
use below code
<?php
$var = 4;
echo $current = (($var > 2) ? "gr than 2" : (($var > 6) ? "gr than 6" : "not gr than 2 or 6") );
?>
This.
echo $current = ($var > 2) ? ($var >6)? "gr than 6":"lower than 6" : "lower than 2 or 6";
You can use () for each conditions..try it..
echo $current = (($var > 2) ? "gr than 2" : (($var > 6) ? "gr than 6" : "not gr than 2 or 6"));
Set the priority
<?php
$var = 4;
echo $current = ($var > 2) ? "gr than 2" : ( ($var > 6) ? "gr than 6" : "not gr than 2 or 6" );
?>
The solution is to use parentheses to group your operators and also alter the order of the conditions a bit:
echo $current = ($var > 2) ?
(($var > 6) ? "gr than 6" : "gr than 2") :
"not gr than 2 or 6 (smaller than 2)";
The problem in your version is that by default it gets grouped like this:
echo $current = (($var > 2) ? "gr than 2" : ($var > 6)) ?
"gr than 6" :
"not gr than 2 or 6";
Which is equal to:
echo $current = ("gr than 2") ?
"gr than 6" :
"not gr than 2 or 6";