Remove all `null` values from an array in PHP
May 17, 2022 ‐ 1 min read
A convenient method to remove all null
values from an array in PHP is by using the array_filter()
function. As the name suggests the method filters a given array, if you don't supply your own filter function PHP filters out all values that evaluate as false
in a condition; empty strings, 0
, false
, null
.
To explicitly only filter out the null
values you should pass your own callback function to the array_filter()
function that only returns false
if a given value is equal to null
.
Using an arrow function that would look like the following:
<?php
$values = ['a', 'b', null, 'c'];
$result = array_filter($values, fn ($value) => !is_null($value));
print_r($result);
// Array
// (
// [0] => a
// [1] => b
// [2] => c
// )
As I mentioned above, if you don't supply a callback function yourself PHP filters out all values that evaluate as false
. So that includes other values besides null
as well. But maybe that's just what you need. In that case, see the example below:
<?php
$values = ['a', '', null, false, []];
$result = array_filter($values);
print_r($result);
// Array
// (
// [0] => a
// )