Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search some text in PHP array

Tags:

arrays

php

search

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

like image 442
Mert S. Kaplan Avatar asked Jan 05 '23 02:01

Mert S. Kaplan


1 Answers

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.

like image 146
Xorifelse Avatar answered Jan 07 '23 15:01

Xorifelse