0

By the way i surprised about this What will this code output and why?

$x = true and false;
var_dump($x);
Rizier123
  • 58,877
  • 16
  • 101
  • 156

2 Answers2

7

Surprisingly to many, the above code will output bool(true) seeming to imply that the and operator is behaving instead as an or.

The issue here is that the = operator takes precedence over the and operator in order of operations, so the statement $x = true and false ends up being functionally equivalent to:

$x = true; // sets $x equal to true true and false; // results in false, but has no affect on anything This is, incidentally, a great example of why using parentheses to clearly specify your intent is generally a good practice, in any language. For example, if the above statement $x = true and false were replaced with $x = (true and false), then $x would be set to false as expected.

saleem ahmed
  • 326
  • 1
  • 5
  • 27
1

As explained here, the = operator has higher precedence than the and operator, causing $x = true to evaluate before true and false does, meaning that $x will take the value of true.

This will give you what you want:

$x = (true and false);
Community
  • 1
  • 1
Frank
  • 664
  • 5
  • 15