tags:

views:

107

answers:

8

My site requires a login that establishes permissions based on the user. In the photo listing of the site, I must determine if a particular photo will be displayed if the user has guest access only. So I thought that this if else statement would work:

if (!($mysql_row['guest_access'] == 'NO') AND ($_SESSION['user_level'] == 'GUEST')) {

  // show the photo if it isn't private and the user isn't a guest

But it doesn't.

However, if I separate this test into three lines then it works just fine.

$is_private_photo = $mysql_row['guest_access'] == 'NO';  
$is_guest = $_SESSION['user_level'] == 'GUEST';
$both_private_and_guest = ($is_private_photo AND $is_guest);

if  (!$both_private_and_guest) {
  // show the photo if it isn't private and the user isn't a guest

What is wrong with the first version?

+2  A: 

The logical not operation needs to be applied to the AND results, but in your code sample it only applied to the first clause (NOT has higher precedence than AND). You can solve it by grouping both conditions:

if (!(($mysql_row['guest_access'] == 'NO' AND ($_SESSION['user_level'] == 'GUEST'))) {
notnoop
+1  A: 

It's because you put the parentheses in the wrong place in your first version. The equivalent form of the second version is

if (!$is_private_photo AND $is_guest)

which is clearly not what you intended.

Michael Myers
+6  A: 

Your first if is

if (!($mysql_row['guest_access'] == 'NO') AND ($_SESSION['user_level'] == 'GUEST'))

Which is actually interpreted like this :

if (
    (!($mysql_row['guest_access'] == 'NO'))
    AND ($_SESSION['user_level'] == 'GUEST')
  )

The ! is only applied to the first condition, not both, because it has a higher level of priority than AND (see Operator Precedence)


Your condition should probably be re-written with some additional parentheses :

if (!(($mysql_row['guest_access'] == 'NO') AND ($_SESSION['user_level'] == 'GUEST')))

So the ! is applied to the whole condition.

Pascal MARTIN
+1 for details.
Michael Myers
A: 

Your '!' is not being applied to the 'AND' statement...it is only being applied to the ($mysql_row['guest_access'] == 'NO') statement.

Ichorus
+2  A: 

The not operator (!) only covers the first condition so either add another bracket, or do this

if ( $mysql_row['guest_access'] != 'NO' AND...
Mark Dickinson
A: 

You are only negating the first condition. Try this:

if (!($mysql_row['guest_access'] == 'NO' AND $_SESSION['user_level'] == 'GUEST')) {
Chandra Patni
A: 

Your negation operator does not apply as expected. You should use something like:

if ( ! (($mysql_row['guest_access'] == 'NO') AND ($_SESSION['user_level'] == 'GUEST')) )

if ( ! ($mysql_row['guest_access'] == 'NO') OR ! ($_SESSION['user_level'] == 'GUEST') )
codaddict
+1  A: 

Make it like this:

if (($mysql_row['guest_access'] != 'NO') AND ($_SESSION['user_level'] != 'GUEST')) {
John Isaacks