문제

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";
?>
도움이 되었습니까?

해결책

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");

다른 팁

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). 
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top