0

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

2
  • Can't confirm. The result would be a collection. Even if you do $filtered->all();, the result is [ "key1" => "value1" "key2" => "value1" 0 => "value2" 1 => "value3" 3 => "value4" 5 => "value2" 6 => "value3" 8 => "key5" ] Commented May 27, 2021 at 11:16
  • I did an array_push and view the JSON on chrome developer tools . That was my result from there. Commented May 27, 2021 at 12:35

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

This does work, well explained and concise. Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.