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.7 (score out of 5, no. of ratings: 3)
Comments
Comment by Ruben Benjamin on 2005-03-02
simple but really excellent. the code is very good than array_search() in php

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