PHP
Recursively Filter Falsy Values from a Nested PHP Array
Clean up a complex PHP array by recursively removing elements considered 'falsy' (null, empty strings, false, 0 except for meaningful '0') from both top-level and nested arrays.
<?php
function array_filter_recursive(array $array): array
{
foreach ($array as $key => $value) {
if (is_array($value)) {
$array[$key] = array_filter_recursive($value);
// If the nested array becomes empty after filtering, remove it
if (empty($array[$key])) {
unset($array[$key]);
}
} elseif (empty($value) && $value !== 0 && $value !== '0') {
// Remove falsy values, but keep 0 and '0' as they might be significant
unset($array[$key]);
}
}
return $array;
}
$data = [
'id' => 1,
'name' => 'Product A',
'description' => null,
'details' => [
'price' => 10.99,
'stock' => 0,
'color' => '',
'options' => [
'size' => 'M',
'material' => null,
'weight' => false
]
],
'tags' => ['php', '', 'web'],
'extra' => false,
'status' => 'active',
'empty_array' => [],
'null_value' => null,
'zero_string' => '0'
];
$cleanedData = array_filter_recursive($data);
print_r($cleanedData);
// Expected Output:
// Array
// (
// [id] => 1
// [name] => Product A
// [details] => Array
// (
// [price] => 10.99
// [stock] => 0
// [options] => Array
// (
// [size] => M
// )
// )
// [tags] => Array
// (
// [0] => php
// [2] => web
// )
// [status] => active
// [zero_string] => 0
// )
How it works: This recursive function `array_filter_recursive` traverses through a potentially nested array. For each element, if it's an array, it calls itself to clean the nested array. If the element is a scalar value, it checks if it's "falsy" (empty, null, false) using `empty()`, with an explicit exception for `0` and `'0'` to keep them if they represent meaningful values. Empty nested arrays are also removed after their content is filtered.