-1

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?

IrfanAnwar
  • 79
  • 1
  • 10

2 Answers2

2

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
);
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thanks, mate, worked like a charm. I will accept the answer in 7 minutes because God knows what validation :D – IrfanAnwar Dec 26 '21 at 21:41
1

Your $search_params is not available within the callback function. You must explicitly pass it with use

$search_params = array_filter(
    $search_params,
    function ($val, $key) use ($search_params) {
        return (isset($search_params[$key]) && $val != 'undefined');
    },
    ARRAY_FILTER_USE_BOTH
);

As of PHP 7.4 you may use arrow functions, which have access to the above scope:

$search_params = array_filter(
    $search_params,
    fn ($val, $key) => isset($search_params[$key]) && $val != 'undefined',
    ARRAY_FILTER_USE_BOTH
);

Read more here:

ozahorulia
  • 9,798
  • 8
  • 48
  • 72