Re: IF statement help

From: Date: Fri, 28 Sep 2001 18:42:49 +0000
Subject: Re: IF statement help
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-69207@lists.php.net to get a copy of this message
A regular expression would be much easier: if (eregi("^(control)[1-9]$", $key)) { // do something } else { // do something else } If you're unfamiliar with regular expressions, we're checking if the string matches the following: 1. it starts with "control". ^ at the beginning of a regex basically means "start of string". The parenthesis are called a bound, which means, in this case, the substring "control" must appear at this point. 2. after "control", the next character can be any single digit number between 1 and 9 inclusive. The square brackets in this case mean "one of whatever is in the brackets". In this case, we have a range of characters -- 0 through 9 inclusive. 3. the string ends immediately. The $ sign at the end of a regex signifies the end of the pattern. If the string matches the regex, eregi() returns true. Otherwise, it returns false. That's probably the easiest way. Regular expressions are extremely useful for checking string patterns. Actually, that's basically the whole point of regular expressions. For more regex info, see your man pages on regex (if you're on a unix-like machine). There's lots of tutorials, too. The PHP manual has a bit of details on regexes, too. The definitive source is "Mastering Regular Expressions" by Jeffery E. F. Friedl, published by O'Reilly. J Chesley A Windon wrote: > Hi: > > I have a script with an IF statement that has to check for several control > commands in a single comparison (see below). If any one of the control > commands are present, I will call a function. If none of the commands are > present, I will call a different function. > > My question is: Is there a way to accomplish the same thing without having > this large of an IF statement comparison? > > if (($key=="control1") || ($key=="control2") || > ($key=="control3") || > ($key=="control4") || ($key=="control5") || > ($key=="control6") || > ($key=="control7") || ($key=="control8") || > ($key=="control9")) { > > // do something; > > } else { > > // do somthing else; > > } > > > Thanks, > > Chesley

« previous php.general (#69207) next »