Reputation: 741
Why does the variable $strange
evaluates to true
in the following snippet?
$strange = true and false;
var_dump($strange); // true
Upvotes: 1
Views: 74
Reputation:
As documentation says:
// foo() will never get called as those operators are short-circuit
$a = (false && foo());
$b = (true || foo());
$c = (false and foo());
$d = (true or foo());
And
// The constant true is assigned to $h and then false is ignored
// Acts like: (($h = true) and false)
$h = true and false;
So the false
will be ignored.
Upvotes: 0
Reputation: 4550
I'm no PHP expert, but this seems to be an issue with simple logic...
The expression var_dump($strange);
evaluates and outputs the first argument.
Upvotes: 0
Reputation: 24661
See the documentation:
// The constant true is assigned to $h and then false is executed then and its
// value is and'd with the results of the assignment.
// Acts like: (($h = true) and false)
$h = true and false;
The above example is taken straight from there, and matches your issue exactly.
Upvotes: 0
Reputation: 386331
and
is a low-precedence version of &&
.
$strange = true and false;
is equivalent to
($strange = true) and false;
You want
$strange = (true and false);
or the more appropriate
$strange = true && false;
and
and or
are best reserved when preceding a flow control statement like break
or return
.
foo()
or throw new Exception('foo() returned an error.');
Upvotes: 3
Reputation: 360762
and
and or
in PHP have a LOWER operator precedence then &&
and ||
. Your code is being evaluated as
($strange = true) and false;
These two would have worked:
$strange = true && false;
$strange = (true and false);
Upvotes: 0