PHP Case-Insensitive In_Array Function

PHP case-insensitive in_array function

you can use preg_grep():

$a= array(
'one',
'two',
'three',
'four'
);

print_r( preg_grep( "/ONe/i" , $a ) );

How can I get in_array() case-insensitive?

Well if you can make sure, that the search word is always in lowercase, just also put the array in lower case by looping through all values with array_map() and putting them in lowercase with strtolower(), e.g.

if (in_array('lookupvalue', array_map("strtolower", $array))) {
// do something
}

Case-insensitive array search

array_search(strtolower($search), array_map('strtolower', $array));

array_keys or in_array insensitive doesnt work correctly

Create the array and find the keys with with strtolower:

$wordsExample = array("example1","example2","example3","August","example4");
$lowercaseWordsExample = array();
foreach ($wordsExample as $val) {
$lowercaseWordsExample[] = strtolower($val);
}

if(in_array(strtolower('august'),$lowercaseWordsExample,FALSE))
return "WOHOOOOO";

if(in_array(strtolower('aUguSt'),$lowercaseWordsExample,FALSE))
return "WOHOOOOO";

Another way would be to write a new in_array function that would be case insensitive:

function in_arrayi($needle, $haystack) {
return in_array(strtolower($needle), array_map('strtolower', $haystack));
}

If you want it to use less memory, better create the words array using lowercase letter.



Related Topics



Leave a reply



Submit