1

I am trying to use below code to filter JSON data an it works flawlessly if I give filter

$search_text = '53';
$filter_name ='title';

$expected88 = array_filter($array, function($el) use ($search_text) {
       return ( stripos($el['title'], $search_text) !== false );
     //      return ( stripos($el[$filter_name], $search_text) !== false );
     
        
    });

echo json_encode($expected88,true);

You can see that if I give this $el['title'] in stripos() it works, but if I try to pass $el[$filter_name] it does not work.

I tried several other combination like $el["$filter_name"] $el['.$filter_name.'] but nothing is working -- it's dynamic data that I want to pass variable.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
sonutup
  • 57
  • 7
  • Seemingly related: [How to pass multiple variables to and from a callback function in PHP?](https://stackoverflow.com/q/56747914/2943403) – mickmackusa Mar 25 '23 at 06:00

1 Answers1

2

$filter_name is not available in anonymous function, so you need to use it, same as you do with $search_text:

$expected88 = array_filter($array, function($el) use ($search_text, $filter_name) {
   return ( stripos($el[$filter_name], $search_text) !== false );
});
u_mulder
  • 54,101
  • 5
  • 48
  • 64
  • In `use` you pass any number of variables that will be available in your anonymous function: `use ($v1, $v2, $v3)` or `use ($v1, $v2, $v3, $v4, $v5)`. – u_mulder Mar 14 '20 at 14:02