4

I have tried to search within an array but did not get any result at all.

Suppose I have a array which contains some values.

So when I want to search them, it always return null!

Do not know the reason why!

Suppose this is my array--

$data = Array
    (
    [0] => Array
    (
        [id] => 122
        [name] => Fast and furious 5
        [category] => Game
    )

    [1] => Array
    (
        [id] => 232
        [name] => Battlefield and more 
        [category] => Game
    )

    [2] => Array
    (
        [id] => 324
        [name] => Titanic the legend
        [category] => movie
    )

    [3] => Array
    ....

So I have tried like this--

   $search = 'and'; // what I want to search
   $nameSearch = array_search($search, $data);
   print_r($nameSearch);

Output -- empty

   $search='and'; // what i want to search
   $nameSearch=  array_filter($search, $data);
   print_r($nameSearch);

Output -- empty

The goal is to find the values which matches anything from the array.

Means, if I request "and" in return I should get

Fast and furious 5
Battlefield and more 

Because of of the value contains "and".

toesslab
  • 5,092
  • 8
  • 43
  • 62
Istiak Mahmood
  • 2,330
  • 8
  • 31
  • 73

2 Answers2

5

array_filter and array_search look for exact matches. Combine array_filter with stripos instead if you want partial matches:

$search = 'and';

print_r(array_filter($data,function($a) use ($search) {
    return stripos($a['name'],$search) !== false;
}));
FuzzyTree
  • 32,014
  • 3
  • 54
  • 85
3

This will work for you

 <?php
$array = array('Fast and furious ', 'Titanic the legend', 'Battlefield and more ', 'India', 'Brazil', 'Croatia', 'Denmark');
$search = preg_grep('/and.*/', $array);
echo '<pre>';
print_r($search );
echo '</pre>';
?>