PHP case-insensitive in_array function

前端 未结 11 619
故里飘歌
故里飘歌 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:43

    /**
     * in_array function variant that performs case-insensitive comparison when needle is a string.
     *
     * @param mixed $needle
     * @param array $haystack
     * @param bool $strict
     *
     * @return bool
     */
    function in_arrayi($needle, array $haystack, bool $strict = false): bool
    {
    
        if (is_string($needle)) {
    
            $needle = strtolower($needle);
    
            foreach ($haystack as $value) {
    
                if (is_string($value)) {
                    if (strtolower($value) === $needle) {
                        return true;
                    }
                }
    
            }
    
            return false;
    
        }
    
        return in_array($needle, $haystack, $strict);
    
    }
    
    
    /**
     * in_array function variant that performs case-insensitive comparison when needle is a string.
     * Multibyte version.
     *
     * @param mixed $needle
     * @param array $haystack
     * @param bool $strict
     * @param string|null $encoding
     *
     * @return bool
     */
    function mb_in_arrayi($needle, array $haystack, bool $strict = false, ?string $encoding = null): bool
    {
    
        if (null === $encoding) {
            $encoding = mb_internal_encoding();
        }
    
        if (is_string($needle)) {
    
            $needle = mb_strtolower($needle, $encoding);
    
            foreach ($haystack as $value) {
    
                if (is_string($value)) {
                    if (mb_strtolower($value, $encoding) === $needle) {
                        return true;
                    }
                }
    
            }
    
            return false;
    
        }
    
        return in_array($needle, $haystack, $strict);
    
    }
    

提交回复
热议问题