phpcallbackscopestrposstripos

How to pass multiple variables from global scope into callback scope?


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.


Solution

  • $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 );
    });