|
Testing for one of a list of values.
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)) { ...
[i]Note[/i] - 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, (written 2007-05-22 08:21:20)
Associated topics are indexed under H104 - PHP - Control StatementsH106 - PHP - Arrays
Some other Articles
A Fresh horseReturning multiple values from a function (Perl, PHP, Python)No switch in PythonTraining information - England, Scotland, Wales and IrelandTesting for one of a list of values.From Web to Web 2Back off home with our best wishesThe last tree to leafRegular Express PrimerDrawing hands on a clock face - PHP
|
1916 posts, page by page
Link to page ... 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39 at 50 posts per page
This is a page archived from The Horse's Mouth at
http://www.wellho.net/horse/ -
the diary and writings of Graham Ellis.
Every attempt was made to provide current information at the time the
page was written, but things do move forward in our business - new software
releases, price changes, new techniques. Please check back via
our main site for current courses,
prices, versions, etc - any mention of a price in "The Horse's Mouth"
cannot be taken as an offer to supply at that price.
Link to Ezine home page (for reading).
Link to Blogging home page (to add comments).
|
|