4

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

3 Answers 3

3

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

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.

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

2 Comments

Thanks for the solution. It worked like I wanted after changing the locations of the $haystack and $needle variables.
@MertS.Kaplan Aah yes, I'll update the code as well.
3

Explode your string and then check, if there are any same strings in both arrays.

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

1 Comment

Thanks for the acceptable and simple solution. I think @Xorifelse's solution is better.
3

You can use Regular Expressions - preg_match ('i' means case insensitive) to check if array contains some words

for example:

$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.";
}

1 Comment

Thanks. preg_match is a good method, but it would be better if there is no loop.

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.