I want to array_filter
an array inside a function:
function filter($array, $check){
return array_filter($array,function($val){return $val==$check;});
}
Note: This is a simplified scenario.
This doesn't work, because $check
is not defined in the filter function, but I can't use global $check;
neither because it can't import variables from ONE level up. I also can't pass it as argument.
Any workarounds?
You can use the use
keyword:
function filter($array, $check) {
return array_filter($array, function($value) use ($check) {
return ($value == $check);
});
}
It is essentially the same as using the global
keyword when you want to bring an outside variable into a normal function. The reason you need to use the use
keyword, instead of global
, has to do with how anonymous functions work. In short, they are turned into objects of the Closure class.
function filter($array, $check = $check_global){
return array_filter($array,function($val){return $val == $check;});
}