Remove null values from array php using array_filter

Remove null values from array php using array_filter
Remove null values from array php using array_filter

Remove null values from array php using array_filter. Remove only null values from array and do not remove boolean false, integer zero 0 and blank string.

array_filter – Filters elements of an array using a callback function.

When we use array_filter with default way, without callback function, it removes all conditionally false value. like boolean false, integer zero 0 and blank string.


$mixArr = ['first' => 'firstVal', 'second' => null, 'third' => false, 'four' => 0, 'five' => ''];
$simpleFilter = array_filter($mixArr);
var_dump($simpleFilter);
//array(1) { ["first"]=> string(8) "firstVal" }

In some cases if need to remove null values only from array, use callback function parameter in array_filter. Below is example for Remove null values from array php using array_filter.

Example for remove null values from array php


$nullFilter = array_filter($mixArr, function($val){ return !is_null($val); });
var_dump($nullFilter);
//array(4) { ["first"]=> string(8) "firstVal" ["third"]=> bool(false) ["four"]=> int(0) ["five"]=> string(0) "" }