The in_array() function searches an array for a specific value. Note: If the search parameter is a string and the type parameter is set to TRUE, the search is case-sensitive.
The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.
in_array() function is utilized to determine if specific value exists in an array. It works fine for one dimensional numeric and associative arrays.
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.
function in_arrayi($needle, $haystack) {
return in_array(strtolower($needle), array_map('strtolower', $haystack));
}
From Documentation
you can use preg_grep()
:
$a= array(
'one',
'two',
'three',
'four'
);
print_r( preg_grep( "/ONe/i" , $a ) );
function in_arrayi($needle, $haystack) {
return in_array(strtolower($needle), array_map('strtolower', $haystack));
}
Source: php.net in_array manual page.
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";
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With