How to Remove Null Values From a PHP Array?

In PHP, you can filter out all null values from an array by using the array_filter() function, for example, like so:

// PHP 7.4+
$arr = [null, 'foo', '', 0, null, 'bar'];
$filteredArr = array_filter($arr, fn ($item) => null !== $item);

echo print_r($filteredArr, true); // [1 => 'foo', 2 => '', 3 => 0, 5 => 'bar']

You can rewrite the callback to array_map() without arrow function to make it compatible with earlier versions of PHP.

This would return a new array only with the values that return true in the array_filter() function (which in this case are all non-null values). However, as you might have noticed in the example above, the array keys are preserved (which results in gaps in the indexed array). If you wish to reindex the array, then you can use the array_values() function on the resulting array like so:

$arr = [null, 'foo', '', 0, null, 'bar'];
$filteredArr = array_filter($arr, fn ($item) => null !== $item);
$reindexArr = array_values($filteredArr);

echo print_r($reindexArr, true); // [0 => 'foo', 1 => '', 2 => 0, 3 => 'bar']

Alternatively, you may also use the splat operator (...) to unpack the array into a new array like so:

$arr = [null, 'foo', '', 0, null, 'bar'];
$filteredArr = array_filter($arr, fn ($item) => null !== $item);
$reindexArr = [...$filteredArr];

echo print_r($reindexArr, true); // [0 => 'foo', 1 => '', 2 => 0, 3 => 'bar']

Please note that using the splat operator (...) might not be performant with large arrays.


This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.