Array remove empty entries

Removes empty entries from a array recursivly

Snippet information

Author:
Jonas John

License:
Public Domain

Language:
PHP

Created:
03/28/2006

Updated:
03/28/2006

Tags:
,


function array_remove_empty($arr){
    $narr = array();
    while(list($key, $val) = each($arr)){
        if (is_array($val)){
            $val = array_remove_empty($val);
            // does the result array contain anything?
            if (count($val)!=0){
                // yes :-)
                $narr[$key] = $val;
            }
        }
        else {
            if (trim($val) != ""){
                $narr[$key] = $val;
            }
        }
    }
    unset($arr);
    return $narr;
}


Found a bug? Or do you have a better solution for this?
Feel free to leave a message:

Add a comment


Leave a comment

deane April 02, 2010 at 08:49
what about:

array_filter($the_array);

ta da!
fritz July 30, 2009 at 15:06
array_filter called without a callback is NOT identical to Jonas' function - array_filter will get rid of '0' as well, since they evaluate to false.
nilesh July 17, 2009 at 14:39
shortcut to remove empty values from array:

$a = array('a','','c');

$a = array_diff($a, array(''))

// $a will be array('a','c');
Peter April 05, 2008 at 09:31
Simon, in PHP compact() doesn't do what you'd guess it does; it actually creates an array out of a list variables. array_filter() called without a callback however has an identical effect to Jonas' function.
Simon November 17, 2007 at 15:15
Why not use 'compact();' ?