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

Michael Pemberton evolt at mpember.net.au
Sat Jan 8 07:49:40 CST 2005


Tim Burgan wrote:
> Hello,
> 
> 
> 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") )
>  {
>     // ...
>  }
> ?>
> 
> And also:
> 
> <?php
>  if ( ($_POST['usertype'] != "student" || "staff" || "admin" )
>  {
>     // ...
>  }
> ?>
> 
> I must be using the OR operator the wrong way. Can someone please 
> correct me on this.
> 
> Thanks very much for your time.
> 
> 
> Regards
> 
> Tim Burgan
> 
> 

Try:

$exclude = array("student", "staff", "admin");

if (in_array($_POST['usertype'], $exclude) != true) {
/// -> REST OF YOUR CODE
}

Hopefully this does what you need and leaves room for additional entries 
for comparison when needed.

BTW, the reason who were having problems with the original code was 
because of the logic being incorrect.  The reason for this is that if 
'usertype' == "admin", then both of the first conditions are met and the 
section will be executed.  I think you are not really looking for 
something that is not A or B or C, you are looking for something that is 
'not A' AND 'not B' AND 'not C'.  The result is an equation that goes 
like this:

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

OR THIS

if ( !(($_POST['usertype'] == "student") || ($_POST['usertype'] == 
"staff") || ($_POST['usertype'] == "admin")) )

Hopefully this make sense.  Tt is 12:45am and I could just be rambling.

-- 
Michael Pemberton
evolt at mpember.net.au




More information about the thelist mailing list