How can I check an array recursively for empty content like this example:
Array
(
[product_data] => Array
(
[0] => Array
I needed a function to filter an array recursively for non empty values.
Here is my recursive function:
function filterArray(array $array, bool $keepNonArrayValues = false): array {
$result = [];
foreach ($array as $key => $value) {
if (is_array($value)) {
$value = $this->filterArray($value, $keepNonArrayValues);
}
// keep non empty values anyway
// otherwise only if it is not an array and flag $keepNonArrayValues is TRUE
if (!empty($value) || (!is_array($value) && $keepNonArrayValues)) {
$result[$key] = $value;
}
}
return array_slice($result, 0)
}
With parameter $keepNonArrayValues
you can decide if values such 0
(number zero), ''
(empty string) or false
(bool FALSE) shout be kept in the array. In other words: if $keepNonArrayValues = true
only empty arrays will be removed from target array.
array_slice($result, 0)
has the effect that numeric indices will be rearranged (0..length-1).
Additionally, after filtering the array by this function it can be tested with empty($filterredArray)
.