I need to remove empty entries on multilevel arrays. For now I can remove entries with empty sub-arrays, but not empty arrays... confused, so do I... I think the code will h
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.