Domanda

The first php script below does show "exactly seven", but the other one does not. Any idea why?

--- This one work ---

<?
$num = 7;
echo ($num == 7) ? "exactly seven" : "not seven";
?>

--- This one does not ---

<?
$num = 7;
echo ($num == 7) ? "exactly seven" : ($num > 7) ? "more than seven" : "less than seven";
?>
È stato utile?

Soluzione

It's called precedence of operators. Add some parenthesis to ensure things happen in the right order, e.g.

$num = 7;
echo ($num == 7) ? "exactly seven" : (($num > 7) ? "more than seven" : "less than seven");

Altri suggerimenti

The result of the first part of the expression, ($num == 7) ? "exactly seven" : ($num > 7) is used as input for the other one.

So the expression can be read as echo "exactly seven" ? "more than seven" : "less than seven";.

Since "exactly seven" evaluates to boolean true, the echoed value is "more than seven".

As it's been said, it's in the precedence of operators. The behavior of your line of code

echo ($num == 7) ? "exactly seven" : ($num > 7) ? "more than seven" : "less than seven";

is called the Non-obvious ternary behavior. The evaluation happens from left to right so

1. echo (expr1) ? (expr2) : (expr3) ? (expr4) : (expr5)
2. evaluates the first ternary operator `?` to 
   echo (expr2) ? (expr4) : (expr5) 
   //because expr1 was TRUE ($num == 7)
3. and since the expr2 is "exactly seven" it finally evaluates to 
   echo (expr4). 
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top