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

Phil Turmel philip at turmel.org
Sat Jan 8 07:23:05 CST 2005


Tim,

Your first try is syntactically acceptable, but will always be true, 
since the OR operator returns true if any expression fed to it is true.

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

You have to be careful translating sloppy human languange "and/or" 
wording since it doesn't usually match formal logic.  Your verbage:

 > ...test if a variable is not equal to
 > "student", "staff", or "admin"..

would be most directly translated to:

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

Which, thanks to DeMorgan, can also be rearranged to:

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

Your other attempt will not work with any comparision operator, as PHP 
needs a complete comparison for each item in an expression.  PHP doesn't 
give a syntax error since it helpfully tries to convert the second and 
third strings into integers, ending up with zeros (false).  If you 
really want to list individual items without repeating the comparison 
operator, use --switch-- instead of --if--, like this:

switch ($_POST['usertype']) {
     case "student":
     case "staff":
     case "admin":
         break;
     default:
	// ...
     }

HTH,

Phil Turmel

Tim Burgan wrote:
> 
> Here's what I tried.. that didn't work:
> 
> <?php
>  {
>     // ...
>  }
> ?>
> 
> 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
> 
> 


More information about the thelist mailing list