Array remove empty entries

Removes empty entries from a array recursivly

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;
}
Snippet Details



array_remove_empty(array(1,2,3, '', array(), 4)) => returns array(1,2,3,4)

Sorry folks, comments have been deactivated for now due to the large amount of spam.

Please try to post your questions or problems on a related programming board, a suitable mailing list, a programming chat-room,
or use a QA website like stackoverflow because I'm usually too busy to answer any mails related
to my code snippets. Therefore please just mail me if you found a serious bug... Thank you!


Older comments:

mestny June 17, 2011 at 08:14
Easy method is: array_diff($array_data, array(''));
Vaibhav Gupta April 04, 2011 at 18:55
best function for removing empty values in array....
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();' ?