2

Why does this evaluate true? $test = true and false;

And this not? $test = (true and false);

With the && operator it both evaluates to false, which is what I also would expect with the and operator. Apparently they are not interchangable, apart from the fact that they have a different precedence.

Youri Thielen
  • 440
  • 4
  • 10
  • http://es1.php.net/manual/en/language.operators.precedence.php – Henrique Barcelos May 21 '13 at 14:59
  • 1
    see http://stackoverflow.com/questions/2803321/and-vs-as-operator – Luca May 21 '13 at 15:01
  • I found the answer in another question: http://stackoverflow.com/a/2803576/1630609 – Youri Thielen May 21 '13 at 15:02
  • `$test = true and false;` does **NOT** evaluate to true, but false. But **it sets $test to true**. The complete statement should evaluate to false, as `$test = true` evaluates to true (and sets $test to true), but the remaining ` and false;` makes the statement evaluate to **false** – nl-x May 21 '13 at 15:12
  • In other words `if ($test = true and false) { /*should not execute */ }` just like `if ($test = (true and false)) { /*should not execute */ }`. In both cases they evaluate to false! – nl-x May 21 '13 at 15:14

2 Answers2

7

"&&" has a greater precedence than "and"

// The result of the expression (true && false) is assigned to $g
// Acts like: ($g = (true && false))
$g = true && false;

// The constant true is assigned to $h and then false is ignored
// Acts like: (($h = true) and false)
$h = true and false;

var_dump($g, $h);

prints false, true

peko
  • 11,267
  • 4
  • 33
  • 48
  • This is useful to make an assignment and a comparison in the same line without parentesis: `if ($a = true and $b)` will assing `true` to `$a` then resolve the logical operation. If the expression is evalutated to `true`, you can use the value of `$a` in the `if` block scope. This is equivalent to: `if (($a = true) && $b)`. – Henrique Barcelos May 21 '13 at 15:05
  • short and clear answer. This is what we need in stack overflow. – Stranger Jun 14 '16 at 04:41
4

They are the same except for Precedence

&& > = > and in the precedence table so your first example is equivalent to: ($test = true) and false;

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335