PHP case-insensitive in_array function

前端 未结 11 618
故里飘歌
故里飘歌 2020-11-29 19:52

Is it possible to do case-insensitive comparison when using the in_array function?

So with a source array like this:

$a= array(
 \'one\'         


        
11条回答
  •  一向
    一向 (楼主)
    2020-11-29 20:30

    The obvious thing to do is just convert the search term to lowercase:

    if (in_array(strtolower($word), $array)) { 
      ...
    

    of course if there are uppercase letters in the array you'll need to do this first:

    $search_array = array_map('strtolower', $array);
    

    and search that. There's no point in doing strtolower on the whole array with every search.

    Searching arrays however is linear. If you have a large array or you're going to do this a lot, it would be better to put the search terms in key of the array as this will be much faster access:

    $search_array = array_combine(array_map('strtolower', $a), $a);
    

    then

    if ($search_array[strtolower($word)]) { 
      ...
    

    The only issue here is that array keys must be unique so if you have a collision (eg "One" and "one") you will lose all but one.

提交回复
热议问题