How to remove empty values from multidimensional array in PHP?
The following function worked for my case. We can use a simple recursive function to remove all empty elements from the multidimensional PHP array:
function array_filter_recursive($input){
foreach ($input as &$value){
if (is_array($value)){
$value = array_filter_recursive($value);
}
}
return array_filter($input);
}
Then we just need to call this function:
$myArray = array_filter_recursive($myArray);
Not sure if this is exactly what your looking for.
function array_remove_null($array) {
foreach ($array as $key => $value)
{
if(is_null($value))
unset($array[$key]);
if(is_array($value))
$array[$key] = array_remove_null($value);
}
return $array;
}
Update (corrections):
function array_remove_null($array) {
foreach ($array as $key => $value)
{
if(is_null($value))
unset($array[$key]);
if(is_string($value) && empty($value))
unset($array[$key]);
if(is_array($value))
$array[$key] = array_remove_null($value);
if(isset($array[$key]) && count($array[$key])==0)
unset($array[$key]);
}
return $array;
}
I'm sure better checking and making this more robust might help the solution.
Bit late, but may help someone looking for same answer. I used this very simple approach to;
- remove all the keys from nested arrays that contain no value, then
- remove all the empty nested arrays.
$postArr = array_map('array_filter', $postArr);
$postArr = array_filter( $postArr );