How to find a string in an array in PHP?

前端 未结 6 437
孤独总比滥情好
孤独总比滥情好 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:27

    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
    }
    

提交回复
热议问题