Search for text in a PHP array

How can I find a word in a PHP array?

I try in_array, but it finds 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 should I do it? Is there any function?

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

+4
source share
3 answers

I have to say that I like the simplicity of the Gre_gor 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'];

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

$retval , . , $matches my_array_search , false .

+3

, , - .

$namesArray = array('Peter', 'Joe', 'Glenn', 'Cleveland');
if (array_intersect(explode(' ', 'Peter Parker'), $namesArray))
    echo "There is.";
else
    echo "There is not.";
+3

You can use regular expressions - preg_match ('i' is case insensitive) to check if the array contains multiple words

eg:

$namesArray = array('Peter One', 'Other Peter', 'Glenn', 'Cleveland');
$check = false;

foreach($namesArray as $name) 
{
    if (preg_match("/.*peter.*/i", $name)) {
        $check = true;
        break;
    }
}

if($check) 
{
    echo "There is.";
}
else {
    echo "There is not.";
}
+3
source

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


All Articles