如果我们假设数组只能包含字符串,那么以上是正确的,但数组也可以包含其他数组。 in_array() 函数也可以接受 $needle 的数组,因此如果 $needle 是数组,则 strtolower($needle) 不起作用,如果 $haystack 包含其他数组,则 array_map('strtolower', $haystack) 不起作用数组,但会导致“PHP 警告:strtolower() 期望参数 1 为字符串,给定数组”。
例子:
$needle = array('p', 'H');
$haystack = array(array('p', 'H'), 'U');
所以我创建了一个具有相关方法的帮助类,以进行区分大小写和不区分大小写的 in_array() 检查。我也在使用 mb_strtolower() 而不是 strtolower(),所以可以使用其他编码。代码如下:
class StringHelper {
public static function toLower($string, $encoding = 'UTF-8')
{
return mb_strtolower($string, $encoding);
}
/**
* Digs into all levels of an array and converts all string values to lowercase
*/
public static function arrayToLower($array)
{
foreach ($array as &$value) {
switch (true) {
case is_string($value):
$value = self::toLower($value);
break;
case is_array($value):
$value = self::arrayToLower($value);
break;
}
}
return $array;
}
/**
* Works like the built-in PHP in_array() function — Checks if a value exists in an array, but
* gives the option to choose how the comparison is done - case-sensitive or case-insensitive
*/
public static function inArray($needle, $haystack, $case = 'case-sensitive', $strict = false)
{
switch ($case) {
default:
case 'case-sensitive':
case 'cs':
return in_array($needle, $haystack, $strict);
break;
case 'case-insensitive':
case 'ci':
if (is_array($needle)) {
return in_array(self::arrayToLower($needle), self::arrayToLower($haystack), $strict);
} else {
return in_array(self::toLower($needle), self::arrayToLower($haystack), $strict);
}
break;
}
}
}