Search code examples
laravelassociative-array

Laravel | Filter null values from an associative array


I have an associative array like this:

 $myarray = array(
                'key1' => 'value1'
                'key2' => 'value1','value2','value3', null ,'value4'
                 null
                'key4' => null ,'value2','value3', null
                'key5'
                 null
                );

I want to remove the null values and I tried this:

$collection = collect($myarray);

            $filtered = $collection->filter(function ($value, $key) {
                return $value != null;
            });

The result is this:

     $myarray = array(
                'key1' => 'value1'
                'key2' => 'value1','value2','value3', null ,'value4'
                'key4' => null ,'value2','value3', null
                'key5'
                );

But my desired result is like this:

     $myarray = array(
                'key1' => 'value1'
                'key2' => 'value1','value2','value3','value4'
                 null
                'key4' => 'value2','value3'
                'key5'
                 null
                );

How can I do this?

PS: I'm using Laravel 5.4.36


Solution

  • Your code removes null values from the top-level array. Your "desired result" removes null values from the nested arrays.

    Try this instead:

    foreach ($myarray as $key => $value) {
        if (is_null($key) || !is_array($value)) {
            continue;
        }
    
        $myarray[$key] = array_filter($value);
    }