Why is PHP giving unexpected results?
Ternary operators are evaluated LEFT-TO-RIGHT .
($i == 2) ? "Two" : ($i == 1) ? "One" : "Other"
"Two" ? "One" : "Other" // first part evaluated to "Two"
"One" // non-empty strings evaluate to true
So, you should get One
in your output, not Other
. It's a little tricky.
Wise words from manual :
It is recommended to avoid ternary expressions. PHP's behavior when using multiple ternary operators within a single operator is not obvious.
source to share
An explanation has already been provided by @light, but you need extra parentheses to get the result:
$i = 3;
$result = ($i == 2) ? "Two" : (($i == 1) ? "One" : "Other");
echo $result, PHP_EOL;
$i = 2;
$result = ($i == 2) ? "Two" : (($i == 1) ? "One" : "Other");
echo $result, PHP_EOL;
$i = 1;
$result = ($i == 2) ? "Two" : (($i == 1) ? "One" : "Other");
echo $result, PHP_EOL;
source to share
This is because C # is strongly typed and requires a boolean to be the first argument of a ternary operator, whereas PHP is loosely typed and basically every value can be converted to its boolean equivalent. In addition, ternary operators are evaluated from left to right. What does it mean?
In C #, we need a boolean on the left-most side of the statement, so this is an expression:
String result = (i == 2) ? "Two" : (i == 1) ? "One" : "Other" ;
will be evaluated in the following order:
String result = (i == 2) ? "Two" : ((i == 1) ? "One" : "Other");
i==2
is equal true
, so "Two"
will be assigned as the final result. It looks a little different in PHP. We can interpret this expression:
$result = ($i == 2) ? "Two" : ($i == 1) ? "One" : "Other";
like this
$result = (($i == 2) ? "Two" : ($i == 1)) ? "One" : "Other";
$i
is 2, so the value "Two"
will be the result of the first expression. Non-empty string values in PHP are true, so the final result will be "One".
source to share