PHP case-insensitive in_array function
Is it possible to do case-insensitive comparison when using the in_array
function?
So with a source array like this:
$a= array(
'one',
'two',
'three',
'four'
);
The following lookups would all return true:
in_array('one', $a);
in_array('two', $a);
in_array('ONE', $a);
in_array('fOUr', $a);
What function or set of functions would do the same? I don't think in_array
itself can do this.
Solution 1:
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.
Solution 2:
function in_arrayi($needle, $haystack) {
return in_array(strtolower($needle), array_map('strtolower', $haystack));
}
From Documentation
Solution 3:
you can use preg_grep()
:
$a= array(
'one',
'two',
'three',
'four'
);
print_r( preg_grep( "/ONe/i" , $a ) );