Removing empty items from a single-level array is something trivial in PHP; but it is not so if our array has 2 levels or more. The following function removes empty items from an (multidimensional) array, and returns the resulting array. Please notice that the use of recursion is required because of the array can be of an unknown number of levels, that is, arrays inside the cells of the array, an so on.
This function is useful when by instance, we have a search-form and the user can enter some optional criteria.
// If it is an element, then just return it
if (!is_array($input)) {
return $input;
}
$non_empty_items = array();
foreach ($input as $key => $value) {
// Ignore empty cells
if($value) {
// Use recursion to evaluate cells
$non_empty_items[$key] = array_non_empty_items($value);
}
}
// Finally return the array without empty items
return $non_empty_items;
}
By example, if we pass the following array to the function:
‘country’ => ‘CO’,
‘region’ => ”,
‘city’ => ”,
‘features’ => array(
‘home’ => array(‘garden’, ‘bedrooms’=>3),
‘beach’ => array(‘no_more_than’=>30, ‘yachts_rental’),
’supermarkets’ => ”,
‘discotheque’ => ”
)
);
Then we will obtain an array without empty items, like this:
August 29, 2009 at 05:42
Great work guys this worked well for me
Thanks for this good code..
November 26, 2009 at 18:34
Be careful with this line:
if($value) {}
$value could be false or could be 0. Both are evaluated by php as false, but they are not empty values.
Better would be
if(empty($value)){}
November 26, 2009 at 18:37
Oh, I’m wrong.. 0 and false are also considered false by the “empty” function. I guess $value != ” would then be the correct condition.