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
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 stripos($needle, $haystack) !== false; make the function case insensitive
    return strpos($needle, $haystack) !== false;
  });
  return empty($matches) ? false : $matches;
}
$namesArray = ['Peter', 'Glenn', 'Meg', 'Griffin'];
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With