[thelist] [php] Using the OR operator in an IF statement

Juha Suni juha.suni at ilmiantajat.fi
Mon Jan 10 02:40:53 CST 2005


Tim Burgan wrote:
> Can someone please correct me on my efforts below.
> If I have a condition where I want to test if a variable is not equal
> to "student", "staff", or "admin".. what's the simplest was to
> achieve that?
>
> Here's what I tried.. that didn't work:
>
> <?php
>   if ( ($_POST['usertype'] != "student") || ($_POST['usertype'] !=
> "staff") ||  ($_POST['usertype'] != "admin") )
>   {
>      // ...
>   }

The error lies not within your code (which is typed perfectly correct in the
example above), but rather within your logic. Reading out in plain language
the condition above:

if usertype is not "student", OR usertype is not "staff", OR usertype is not
"admin"

Now read the above through with thought. It will always return true, no
matter what the value of usertype. If usertype is "student", the first
condition will return false, but the last two will both return true,
therefore the entire condition returns true (because you are using the OR
operator, meaning if ANY of the conditions return true, the whole condition
returns true).

What you should be doing is:

if usertype is not "student", AND usertype is not "staff", AND usertype is
not "admin"

Meaning that if ALL of the conditions return true, the whole condition
returns true, otherwise it returns false.

so:

if ( ($_POST['usertype'] != "student") && ($_POST['usertype'] != "staff") &&
($_POST['usertype'] != "admin") )
  {
    // stuff
  }

You can also leave out the extra set of parentheses:

  if ($_POST['usertype'] != "student" && $_POST['usertype'] != "staff" &&
$_POST['usertype'] != "admin")
  {
     // stuph
  }

HTH

-- 
Suni



More information about the thelist mailing list