Mert S. Kaplan Mert S. Kaplan - 29 days ago 6
PHP Question

Search some text in PHP array

How can I search a word in a PHP array?

I try

in_array
, but it find just exactly the same values.

<?php
$namesArray = array('Peter', 'Joe', 'Glenn', 'Cleveland');
if (in_array('Peter Parker', $namesArray)) {echo "There is.";}
else {echo "There is not.";}


I want this instance to return true. How can I do it? Is there any function?

Snippet: https://glot.io/snippets/ek086tekl0

Answer

I have to say I like the simplicity of Gre_gor's answer, but for a more dynamic method you can also use array_filter():

function my_array_search($array, $needle){
  $matches = array_filter($array, function ($haystack) use ($needle){
    // return strpos(strtolower($needle), strtolower($haystack)) !== false; make the function case insensitive
    return strpos($needle, $haystack) !== false;
  });

  return empty($matches) ? false : $matches;
}


$namesArray = ['Peter', 'Glenn', 'Meg', 'Griffin'];

Examples:

if(my_array_search($namesArray, 'Glenn Quagmire')){
   echo 'There is'; // Glenn
} else {
   echo 'There is not';
}

// optionally:
if(($retval = my_array_search($namesArray, 'Peter Griffin'))){
   echo 'There is';
   print_r($retval); // Peter, Griffin.
} else {
   echo 'There is not';
}

Now $retval is optional, it captures an array of matching subjects. This works because if the $matches variable in my_array_search is empty, it returns false instead of an empty array.

Comments