PHP - How to remove empty entries of an array recursively?
Try this code:
<?php
function array_remove_empty($haystack)
{
foreach ($haystack as $key => $value) {
if (is_array($value)) {
$haystack[$key] = array_remove_empty($haystack[$key]);
}
if (empty($haystack[$key])) {
unset($haystack[$key]);
}
}
return $haystack;
}
$raw = array(
'firstname' => 'Foo',
'lastname' => 'Bar',
'nickname' => '',
'birthdate' => array(
'day' => '',
'month' => '',
'year' => '',
),
'likes' => array(
'cars' => array('Subaru Impreza WRX STi', 'Mitsubishi Evo', 'Nissan GTR'),
'bikes' => array(),
),
);
print_r(array_remove_empty($raw));
I think this should solve your problem.
$retArray =array_filter($array, arrayFilter);
function arrayFilter($array) {
if(!empty($array)) {
return array_filter($array);
}
}
Here is my solution, it will remove exactly specified list of empty values recursively:
/**
* Remove elements from array by exact values list recursively
*
* @param array $haystack
* @param array $values
*
* @return array
*/
function array_remove_by_values(array $haystack, array $values)
{
foreach ($haystack as $key => $value) {
if (is_array($value)) {
$haystack[$key] = array_remove_by_values($haystack[$key], $values);
}
if (in_array($haystack[$key], $values, true)) {
unset($haystack[$key]);
}
}
return $haystack;
}
You can use it like this:
$clean = array_remove_by_values($raw, ['', null, []]);
Note, it removes empty sub arrays if you pass []
as one of values.