4
$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" ?

2
  • 6
    in_array is case-sensitive, so 'home' != 'Home' us1.php.net//manual/en/function.in-array.php Commented Jun 16, 2014 at 3:51
  • Just wanted to make a notice here. Do not forget about type comparison - for example in_array(0, array('Home', 'Design')) will return true while in_array(0, array('Home', 'Design'), true) won't Commented Jun 16, 2014 at 5:02

2 Answers 2

2

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) );
}

Demo

Sign up to request clarification or add additional context in comments.

Comments

1

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.

  • preg_grep: 2.9802322387695E-5 sec
  • array_map: 1.3828277587891E-5 sec

1 Comment

-1 for using regex when built-in functions work fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.