Бортовой журнал Ктулху

PHP array_filter() and 0 in array

If we have an array in PHP with one of its values equal to 0, after array_filter(), this value is removed. But sometimes we consider 0 a valid value. 

The second argument of this function helps us. We will write a callback function with a custom filter for empty values, excluding zero.

 

$array = [0,1,2,3,4];
$result = array_filter($array);
// [1,2,3,4]
$result1 = array_filter($array, function($value) {
 return $value !== null && $value !== false && $value !== '';
});
// [0,1,2,3,4]