So The below code works as expected and filters out null values and string "undefined" I was getting in my request
$search_params = array_filter(
$search_params,
function ($val, $key) {
return (isset($val) && $val != 'undefined');
},
ARRAY_FILTER_USE_BOTH
);
But when I try to do below the function never returns the filtered array e.g always false is returned
$search_params = array_filter(
$search_params,
function ($val, $key) {
return (isset($search_params[$key]) && $val != 'undefined');
},
ARRAY_FILTER_USE_BOTH
);
I was wondering what is causing this behavior, is this some kind of context thing?
The global variable $search_params
is not in scope inside the function. Use the use()
directive to indicate variables that should be inherited into the function's scope.
$search_params = array_filter(
$search_params,
function ($val, $key) use ($search_params) {
return (isset($search_params[$key]) && $val != 'undefined');
},
ARRAY_FILTER_USE_BOTH
);