Main Content

Testing for one of a list of values.

Archive - Originally posted on "The Horse's Mouth" - 2007-05-22 08:21:20 - Graham Ellis

Question [PHP] When you have a string of conditions in an 'if' clause and one side of the conditional expression is the same in each condition, is there any shortcut to avoid writing out every expression in full. For examples, rather than writing
if(($name!='Lisa')&&($name!='Leah')&&($name!='Christine')) {
can I write
if($name!=('Lisa'||'Leah'||'Christine')) {

Answer The short answer is "no - you must write it all out if you're using the != operator". In Perl 6 (different language) you WILL have a shortened syntax for this sort of thing but that's highly unusual. But lets' take a wider look at other alternatives.

In php you could write
if (!ereg ('^(Lisa|Leah|Christine)$,$name)) { ....
although that would be slighly less efficient at run time.

I do worry about hardcoding data such as people's names into a program. When Lisa decides she now wants to be called by a different name, or when Chloe joins the team, you're back to the code! Your code would be more maintainable if you had an array of names in a separate file. You could compromise with something like:
$people = array("Hermione","Bob","Sally");
if (in_array($name,$people)) { ...


Note - if you're reading your data into $name from a MySQL database, the INoperator used in a WHERE clause will allow you to filter your data before it ever reaches your PHP variables.