How to Remove Null Values From a PHP Array?

Filtering out all null values from a PHP array

To filter out all null values from a PHP array, you can use the array_filter() function with a callback. When the return value of this callback function is true, the current value from the original array is added to the resulting array. Therefore, to add all non-null values to the resulting array you can check in the callback function if the current value is not null like so:

$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']

As you can see from the result, 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.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.