$array = ('Home', 'Design', 'Store');
$str = 'home';
if (in_array($str, $array)) {
die("Match");
} else {
die("No Match");
}
Result is "No Match" => How to fix it to result is "Match" ?
As stated Mike K in_array() is case sensitive, so you can change cases for every array element and the needle to the lower case (for example):
function in_array_case_insensitive($needle, $array) {
return in_array( strtolower($needle), array_map('strtolower', $array) );
}
Try using preg_grep which—as the manual states:
Return array entries that match the pattern
Your code reworked to use it:
$array = array('Home', 'Design', 'Store');
$str = 'home';
if (preg_grep( "/" . $str . "/i" , $array)) {
die("Match");
} else {
die("No Match");
}
Or if somehow regex seems like a bit much, you can use array_map with strtolower to normalize your data for an in_array check like this:
$array = array('Home', 'Design', 'Store');
$str = 'home';
if (in_array(strtolower($str), array_map('strtolower', $array))) {
die("Match");
} else {
die("No Match");
}
ADDITION: I made a claim in comments that preg_match would be faster than array_map, but doing some tests online with my code shows that is not the case here at all. So use whichever function you feel better with. Speed seems to favor array_map.
in_arrayis case-sensitive, so 'home' != 'Home' us1.php.net//manual/en/function.in-array.phpin_array(0, array('Home', 'Design'))will returntruewhilein_array(0, array('Home', 'Design'), true)won't