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?
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.
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-- .
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.
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.
&&
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With