Remove Empty Array Elements in PHP


From the array_filter docs:

If no callback is supplied, all empty entries of array will be removed. See empty() for how PHP defines empty in this case.

So the snippet removes anything that PHP regards as empty(), including false, 0, '0' etc., so be warned it may not work out of the box for your use case.

An optional custom filter function can be supplied in order to tailor the filter logic to your needs. For example, if you need to keep instances of 0, the callback could be:

array_filter($myArray, function($val) {
    return ! empty($val) || $val === 0;

Or if there are zeros stored as strings in the array which need to be kept (it's a wild world out there):

array_filter($myArray, function ($val) {
    return ! empty($val) || $val === 0 || $val === '0';


Using array_values() on the Result

Use array_values on the result because array_filter doesnt reindex the array (which can be a problem depending on how the array is processed downstream, (ex. if any code is expecting the array to have numerical incrementing indexes)).


Using strlen as the Optional Callback

There is another option to use PHP's strlen as the callback which retains numerical 0 (zero) values:

// removes null, false, and empty strings, but leaves 0 (zero) values
$result = array_filter( $array, 'strlen' );


 PHP  PHP snippets  PHP one-liners  PHP arrays