How to find a string in an array in PHP?

前端 未结 6 436
孤独总比滥情好
孤独总比滥情好 2020-12-10 05:11

I have an array:

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

and a string variable:

$st         


        
6条回答
  •  春和景丽
    2020-12-10 05:23

    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;
       }
    }
    

提交回复
热议问题