PHP Conditional logic, specific order?

I have a conditional statement that goes like this:

if ($_POST['password'] == $_POST['repeat'] && $_SESSION['type'] == "admin")

But let's say I also want the conditional value true for users with the type "superuser" (instead of "admin").

Therefore, I could, for example, write:

if ($_POST['password'] == $_POST['repeat'] && $_SESSION['type'] == "admin" || $_SESSION['type'] == "superuser")

But if we assume that PHP reads conditional expressions and equations from left to right, then for the "superuser" it is possible for the conditional result to be evaluated as true, even if the "password" and "repeat" are not equal, since we place imaginary brackets around the two operands next to "& &", right?

I could add brackets to encapsulate the two operands for "||", but I remember a little that I might have tried something in the past, and if it were ineffective.

Is there a better way to do this? Do the brackets really work (so the conclusion is that my memory is defective?) [Memory leak? Heh.])

Thanks!

+4
source share
4 answers

Yes, brackets will override the fact that && has a higher priority than || .

+3
source

Not tested, but try the following:

 if ($_POST['password'] == $_POST['repeat'] && ($_SESSION['type'] == "admin" || $_SESSION['type'] == "superuser")) 
0
source

Enable admin check () and OR to check type. The superuser must first be verified for optimal code.

 ($_SESSION['type'] == "superuser" || ($_POST['password'] == $_POST['repeat'] && $_SESSION['type'] == "admin") ) 
0
source

To get what you want, you can:

 if (($_POST['password'] == $_POST['repeat']) && ($_SESSION['type'] == "admin" || $_SESSION['type'] == "superuser")) 

What will be evaluated as true when passwords match, and if the user type is an administrator or superuser.

Or, in more detail:

 $valid_password= $_POST['password'] == $_POST['repeat']; $valid_user= $_SESSION['type'] == "admin" || $_SESSION['type'] == "superuser"; if ($valid_password && $valid_user) // Do something 
0
source

Source: https://habr.com/ru/post/1299386/


All Articles