How to compare string matching in an array?

$array = ('Home', 'Design', 'Store');
$str = 'home';
if (in_array($str, $array)) {
   die("Match");
} else {
   die("No Match");
}

Result " No Match" => How to fix this, result " Match"?

+4
source share
2 answers

As indicated, Mike K is in_array()case sensitive, so you can change cases for each element of the array and needle in lower case (for example):

function in_array_case_insensitive($needle, $array) {
     return in_array( strtolower($needle), array_map('strtolower', $array) );
}

Demo

+2
source

Try using preg_grepwhich, as indicated in the manual:

Returns array entries matching pattern

Your code has been reworked to use it:

$array = array('Home', 'Design', 'Store');
$str = 'home';
if (preg_grep( "/" . $str . "/i" , $array)) {
   die("Match");
} else {
   die("No Match");
}

, - , array_map strtolower, in_array, :

$array = array('Home', 'Design', 'Store');
$str = 'home';
if (in_array(strtolower($str), array_map('strtolower', $array))) {
   die("Match");
} else {
   die("No Match");
}

: , preg_match , array_map, , . , . array_map.

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

Source: https://habr.com/ru/post/1544690/


All Articles