Molecular Man
Molecular Man

Reputation: 22386

Why (false and false or true) returns true

var_dump(false and false || true);
// result: bool(false)

(false and false || true) returns false as expected.

var_dump(false and false or true);
// result: bool(true)

but (false and false or true) returns true. I have no logical explanation why this is happening.

Upvotes: 2

Views: 466

Answers (3)

Fabien Papet
Fabien Papet

Reputation: 2319

&& and || have higher precedence on and and or

You can see Operator precedence on PHP documentation

So

<?php 
var_dump(false and false || true);
// eq: false and (true or false) => false

var_dump(false and false or true);
// eq: (false and false) or true => true

Upvotes: 9

Divi
Divi

Reputation: 7701

Even though logically || and or are the same, their precendnce is not.

|| is of a higher precedence than OR, therefore they are interpreted differently in your 2 statements. I guess if you add a bracket around, it will have the same results:

(false and (false || true));

OR

(false and (false or true));

More here

Upvotes: 0

pavel
pavel

Reputation: 27072

Look at http://php.net/manual/en/language.operators.precedence.php

When we sort operators by priority, it´s:

&& > || > AND > OR

And it´s answer to your question. || has higher priority than AND.

I suppose you to use only one 'type' of logical operators, use && and || or and and or. Don´t combine them.

Upvotes: 1

Related Questions