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".

0

2 Answers 2

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;
}));
Sign up to request clarification or add additional context in comments.

8 Comments

thanks a lot for your great answer, but i am keep getting an error like Warning: stripos() expects parameter 1 to be string, array given for the line *return stripos($a,$search) !== false;
@ChristoferHansen the error seems to indicate that $data is an array of arrays as opposed to an array of strings as it is in your example
@yes it is an array of a array
@ChristoferHansen in that case you'll need to specify the key containing the string i.e. return stripos($a['title'],$search) !== false;
i am getting empty values, i have update my question values can u kindly have a look, please
|
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>';
?>

3 Comments

nice, preg_grep is cleaner than combining array_filter with stripos
@FuzzyTree But preg_grep will have it's Limits for complex Arrays - array_filter is more versatile.
@marius thanks for your answer, but it will not work for me cause i always need the post values

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.