PHP case-insensitive in_array function

前端 未结 11 562
故里飘歌
故里飘歌 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:28
    $a = [1 => 'funny', 3 => 'meshgaat', 15 => 'obi', 2 => 'OMER'];  
    
    $b = 'omer';
    
    function checkArr($x,$array)
    {
        $arr = array_values($array);
        $arrlength = count($arr);
        $z = strtolower($x);
    
        for ($i = 0; $i < $arrlength; $i++) {
            if ($z == strtolower($arr[$i])) {
                echo "yes";
            }  
        } 
    };
    
    checkArr($b, $a);
    
    0 讨论(0)
  • 2020-11-29 20:28
    $user_agent = 'yandeX';
    $bots = ['Google','Yahoo','Yandex'];        
            
    foreach($bots as $b){
         if( stripos( $user_agent, $b ) !== false ) return $b;
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-29 20:33

    you can use preg_grep():

    $a= array(
     'one',
     'two',
     'three',
     'four'
    );
    
    print_r( preg_grep( "/ONe/i" , $a ) );
    
    0 讨论(0)
  • 2020-11-29 20:34

    Say you want to use the in_array, here is how you can make the search case insensitive.

    Case insensitive in_array():

    foreach($searchKey as $key => $subkey) {
    
         if (in_array(strtolower($subkey), array_map("strtolower", $subarray)))
         {
            echo "found";
         }
    
    }
    

    Normal case sensitive:

    foreach($searchKey as $key => $subkey) {
    
    if (in_array("$subkey", $subarray))
    
         {
            echo "found";
         }
    
    }
    
    0 讨论(0)
  • 2020-11-29 20:35
    function in_arrayi($needle, $haystack) {
        return in_array(strtolower($needle), array_map('strtolower', $haystack));
    }
    

    Source: php.net in_array manual page.

    0 讨论(0)
提交回复
热议问题