Is it possible to do case-insensitive comparison when using the in_array
function?
So with a source array like this:
$a= array(
\'one\'
$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);
$user_agent = 'yandeX';
$bots = ['Google','Yahoo','Yandex'];
foreach($bots as $b){
if( stripos( $user_agent, $b ) !== false ) return $b;
}
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.
you can use preg_grep():
$a= array(
'one',
'two',
'three',
'four'
);
print_r( preg_grep( "/ONe/i" , $a ) );
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";
}
}
function in_arrayi($needle, $haystack) {
return in_array(strtolower($needle), array_map('strtolower', $haystack));
}
Source: php.net in_array manual page.