Thursday, November 18, 2010

Goodbye OR

There are times in PHP when you want a true condition based on whether or not a variable matches one of many values. I used to just link many conditionals together using the OR (||) operator:

if($name == "Bob" || $name == "Andy" || $name == "Heidi" || $name == "Cindy") {
    //perform stuff here
}


This is fine when you only have a few values to check, but if you have to check the variable against more than a handful, this can get tedious. So, now what I do is I create an array of values that I want to check against. Then I use the in_array() function like so:

//define the array
$names = Array("Bob","Andy","Heidi","Cindy");

//now we use in_array() to check the variable
if(in_array($name,$names)){
    //perform stuff here
}


And that's that. You can even put the array into the if statement if you desire:

if(in_array($name,Array("Bob","Andy","Heidi","Cindy")){
    //perform stuff here
}

No comments:

Post a Comment