header
 
     
 
pixel
pixel pixel

Searching through an array

If I need to check if a variable could be one of many, rather than use the clunky method of multiple conditions:
if ($variable == "this" OR $variable == "that" OR $variable == "those")
I find it more elegant to place all the variables in an array then search the array:
<?php
$listofitems 
= array("this""that""those");
if (
in_array($variable$listofitems))
?>
Note - in_array returns a 1 if found, a 0 if not found. I used to use array_search which returns the index of the found item but that always gave a negative result if the found item was the first item in the array (eg - with index 0).

Unhelpful Helpful Rating 3.1 (score out of 5, no. of ratings: 20)
Comments
Comment by Ruben Benjamin on 2005-03-02
simple but really excellent. the code is very good than array_search() in php

Comment by nike shoes sale on 2010-08-10
http://www.nikesshox.com Your article are great, will visit very soon

Comment by nike shoes sale on 2010-08-10
http://www.nikesshox.com Your article are great, will visit very soon

Comment by d on 2011-05-11
d

Comment by discount Michael Jordan Shoes on 2010-09-17
Air Jordan Shoes are always so attractive, good quality can ensure the wearer's feet, not only that, the Michael Jordan Shoes has become a fashion, many young people are very fanatical Air Jordan. High price so many people can realize their dreams. Well now, our products directly from third-party products, so we can provide cheap Jordan Basketball Shoes and New Jordan Shoes, high quality, excellent service, come on, give yourself a choice. We offerAir Jordan 1, Air Jordan 2, Air Jordan 3,Air Jordan 4, Air Jordan 5, Air Jordan 6, Air Jordan 7, Air Jordan 8, Air Jordan 9, Air Jordan 10, Air Jordan 11 and so on!

Post a Comment
Name
Email
(optional)
Comment
RatingUnhelpful Helpful
Security Image* (this is just to prevent spam submissions)
Security Image