1

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 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!

Amy
  • 11
  • 1
  • 5
    The *less than* operation is a [binary operation](http://en.wikipedia.org/wiki/Binary_operation). – Gumbo Mar 13 '11 at 20:04
  • 1
    Also see [Why does (0 < 5 <3) return true?](http://stackoverflow.com/questions/4089284/why-does-0-5-3-return-true) – BoltClock Mar 13 '11 at 20:05
  • 1
    @Gumbo: The way it's defined in PHP and most other languages, anyway. Math, Lisp and Python think otherwise. –  Mar 13 '11 at 20:08

2 Answers2

7

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)
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • Thanks, that makes sense...but I actually get an error on Codepad when I use my example code. So either this error is a codepad thing (and wouldn't happen in on an actual server, where the condition would always evaluate to true like you said)... or PHP can't handle evaluating my hypothetical condition: http://codepad.org/E1ID4kVw – Amy Mar 13 '11 at 20:11
  • 1
    PHP's primitive parser can't even consider `::` as a namespace separator, and you want it to handle *that*? – Charles Mar 13 '11 at 20:18
  • @Charles: You have to admit it knows its Hebrew though :) (well, its authors do) – BoltClock Mar 13 '11 at 20:19
0

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

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445