PHP filter value matching filter

I tried to search inside the array, but did not get any result.

Suppose I have an array that contains some values.

Therefore, when I want to search for them, it always returns null!

I do not know 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 tried like this -

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

Exit - Empty

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

Exit - Empty

The goal is to find values ​​that match something from the array.

So if I ask "and" in return, I should get

Fast and furious 5
Battlefield and more 

Because of the value contains "and".

+4
source share
2 answers

array_filterand array_searchlook for exact matches. Combine array_filterwith striposinstead if you need partial matches:

$search = 'and';

print_r(array_filter($data,function($a) use ($search) {
    return stripos($a['name'],$search) !== false;
}));
+4

 <?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>';
?>
+2

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


All Articles