开发者

Why can't I have a PHP condition written as 1<$x<3?

I've dug around a bit, but I can't seem to find a simple answer as to why you can't code something like

<?php 
  $x=2;
  if(1<$x<3) {
    echo "Win!";
    } else {
    echo "Lose!";
  }
?>

My gut says that because PHP reads left-right, it evaluates the first half of the statement (1<$x) and then just sees <3 which is meaningless. I'd just like someone to confirm (or refute) that this is 开发者_C百科the case and that any time you're providing conditions in PHP you have to separate out each one. I don't know if this would be called logic or syntax or something else, but you can write expressions like these in other contexts (like SAS) and have them evaluated, so I'd just like to understand why you can't in PHP. Thanks!


PHP evaluates 1 < $x, then compares the result of that to 3. In other words, if you add brackets, PHP sees it as ((1 < $x) < 3).

If 1 < $x is true, the comparison becomes 1 < 3; if false, it's 0 < 3. This is due to type conversion (from boolean to integer). Both evaluate to true, so the if condition is always satisfied.

You'll indeed have to write it like this instead:

if (1 < $x && $x < 3)


The < and > operators evaluate to boolean values. It was a design choice carried over from C.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜