tags:

views:

3990

answers:

5

Lets assume I have an array in PHP:

$array = array("apple", "banana", "cap", "dog", etc..) up to 80 values.

and a string variable:

$str = "abc";

If I want to check whether this string ($str) is exists in the array or not, I use preg_match function. Which is like this:

$isExists = preg_match("/$str/", $array);

if ($isExists){

    echo "Its exists";
} else {

 echo "Not exixts" 

} ;

Is it the correct way? If the array grows bigger, will it be very slow? Is there any other method? I am trying to scaling down my database traffic. Hope you guys can help..

AFTER GET THE ANSWER: If i have two or more string to compare? How to do that?

+12  A: 
 bool in_array  ( mixed $needle  , array $haystack  [, bool $strict  ] )
Sam McAfee
+4  A: 

If you just need an exact match, use in_array($str, $array) - it will be faster.

Another approach would be to use an associative array with your strings as the key, which should be logarithmically faster. Doubt you'll see a huge difference between that and the linear search approach with just 80 elements though.

If you do need a pattern match, then you'll need to loop over the array elements to use preg_match.


You edited the question to ask "what if you want to check for several strings?" - you'll need to loop over those strings, but you can stop as soon as you don't get a match...

$find=array("foo", "bar");
$found=count($find)>0; //ensure found is initialised as false when no terms
foreach($find as $term)
{
   if(!in_array($term, $array))
   {
        $found=false;
        break;
   }
}
Paul Dixon
+2  A: 

Why not use the built-in function in_array? (http://www.php.net/in_array)

preg_match will only work when looking for a substring in another string. (source)

JohnnyPark
+2  A: 

preg_match expects a string input not an array. If you use the method you described you will receive:

Warning: preg_match() expects parameter 2 to be string, array given in LOCATION on line X

You want in_array:

if ( in_array ( $str , $array ) ) {
    echo 'It exists';
} else {
    echo 'Does not exist';
}
Norse
If I have 2 string, how to match in an array???
roa3
the string like this $var "id1;id2";
roa3
Paul Dixon's answer above answers this quite well.
Norse
+1  A: 

If you have more than one value you could either test every value separatly:

if (in_array($str1, $array) && in_array($str2, $array) && in_array($str3, $array) /* … */) {
    // every string is element of the array
    // replace AND operator (`&&`) by OR operator (`||`) to check
    // if at least one of the strings is element of the array
}

Or you could do an intersection of both the strings and the array:

$strings = array($str1, $str2, $str3, /* … */);
if (count(array_intersect($strings, $array)) == count($strings)) {
    // every string is element of the array
    // remove "== count($strings)" to check if at least one of the strings is element
    // of the array
}
Gumbo