Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple boolean conditions - operator precedence

I encountered a code line that looks like this:

if ($users == 'all' || $_POST['user'] == 1 && $users == 'admins' || $_POST[ 'user' ] == 0 && $users == 'mods') ...

I don't understand how are all these conditions met because there are not parentheses between them :(

Is || more important than && ? Which parts get evaluated first?

like image 601
Alex Avatar asked Nov 15 '11 14:11

Alex


People also ask

What is the order of precedence of Boolean operators?

There are three basic Boolean operators: NOT, AND, OR. XOR is just a simple version of A AND NOT B OR NOT A AND B or (A OR NOT B) AND (NOT A OR B) . So, only these three have common precedence: NOT > AND > OR.

Which Boolean operator has the highest precedence?

The logical-AND operator ( && ) has higher precedence than the logical-OR operator ( || ), so q && r is grouped as an operand. Since the logical operators guarantee evaluation of operands from left to right, q && r is evaluated before s-- .

Which operator has the highest order of precedence?

This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator. Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom.

Which has more precedence * OR?

Certain operators have higher precedence than others; for example, the multiplication operator has a higher precedence than the addition operator. For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.


1 Answers

&& depends of the evaluation of the right expression when left one is true, || doesn't. You could rewrite it to:

if(
    $users == 'all' ||
    ($_POST['user'] == 1 && $users == 'admins') ||
    ($_POST['user'] == 0 && $users == 'mods')
)

And it'll be the same.

like image 92
Ben Avatar answered Nov 04 '22 14:11

Ben