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.
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.
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);
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With