views:

51

answers:

4

Hello everybody,

I have a conditional statement which goes thusly:

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

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

So I could, for example, write:

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

But assuming PHP reads conditionals and equations from the left to the right, it's then possible for a "superuser" to have the conditional evaluate true even if "password" and "repeat" are not equal, since we're placing imaginary brackets around the two operands next to "&&", right?

I could add brackets to encapsulate the two operands for "||", but I recall faintly that I may have tried something in the past, and had it fail spectacularly.

Is there a better way to do this? Do brackets actually work (thus concluding that my memory is faulty? [memory leak? heh.])

Thanks!

+3  A: 

Yes, parentheses will override the fact that && has a higher precedence than ||.

Ignacio Vazquez-Abrams
Cheers for the quick response!
Julian H. Lam
A: 

Haven't tested but try this:

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

Enclose the admin check in () and OR the 'type' check. Superuser should get checked first for optimal code.

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

To get what you want you could:

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

Which would evaluate to true when passwords match and if the user type is admin or super user.

Or, more verbosely:

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