Skip to content

How to filter empty values from a PHP array the easy way

Cutting straight to the point, here’s a quick way with PHP for removing empty values from an array and shifting the indices appropriately. Nothing too fancy but I found it useful at work and figure that I might as well share the tip.

$array = array('apples', 'oranges', '', 'bananas', null);
$filteredarray = array_values( array_filter($array) );
 
print_r($filteredarray);

/*
The above will output:
Array
(
    [0] => apples
    [1] => oranges
    [2] => bananas
)
*/

Note that array_filter() will remove all values that evaluate to FALSE (see converting to boolean). To specify your own filter, you can pass a callback function to array_filter.