Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter recursive array and only remove NULL value

I want to remove all null or blank value but not false and 0 value from recursive array.

function isNotNull($val) {
    if(is_array($val)) {
        $ret = array_filter($val, 'isNotNull');
        return $ret;
    } else {
        return (!is_null($val) && $val !== '');
   }

}

$arr = array_filter($arr, 'isNotNull');

Input:

$arr = array(
"stringKey" => "Abc",
"boolKey" => false,
"zeroKey" => 0,
"blankKey" => '',
"newArr" => array(
    "stringKey2"=>"Abc2", 
    "boolKey2"=>false, 
    "zeroKey2" => 0, 
    "blankKey2"=>"", 
    "blankArr" => array()
    )
);

This give output:

Array
(
    [stringKey] => Abc
    [boolKey] => 
    [zeroKey] => 0
    [newArr] => Array
        (
            [stringKey2] => Abc2
            [boolKey2] => 
            [zeroKey2] => 0
            [blankKey2] => 
            [blankArr] => Array
                (
                )
        )
)

But i want to bellow output:

 Array
(
    [stringKey] => Abc
    [boolKey] => 
    [zeroKey] => 0
    [newArr] => Array
        (
            [stringKey2] => Abc2
            [boolKey2] => 
            [zeroKey2] => 0
        )
)

I used array_filter with callback function but it only filter simple array not multidimensional array. I don't want to use loop.

like image 378
Krishna Kumar Yadav Avatar asked Apr 18 '17 07:04

Krishna Kumar Yadav


People also ask

How do you remove null values from an array?

To remove all null values from an array:Declare a results variable and set it to an empty array. Use the forEach() method to iterate over the array. Check if each element is not equal to null . If the condition is satisfied, push the element into the results array.


1 Answers

You could combine array_map and array_filter in an recursive called function. Something like this could work for you.

function filterNotNull($array) {
    $array = array_map(function($item) {
        return is_array($item) ? filterNotNull($item) : $item;
    }, $array);
    return array_filter($array, function($item) {
        return $item !== "" && $item !== null && (!is_array($item) || count($item) > 0);
    });
}
like image 158
Philipp Avatar answered Oct 09 '22 15:10

Philipp