During PHP development, processing arrays is a very common requirement. One of the typical scenarios is: we want to remove elements in the array with boolean value false , such as false , 0 , "" (empty string), null , empty array, etc. At this time, the array_filter() function is a very useful tool.
array_filter() is a built-in function of PHP. Its function is to filter each element in the array with a callback function and return a new array of all elements tested by the callback function. If the callback function is not passed, it will automatically remove all elements with a boolean value of false .
array_filter(array $array, ?callable $callback = null, int $mode = 0): array
$array : The original array to filter
$callback (optional): Custom callback function
$mode (optional): can control whether the key or value passed to the callback function or both
When we do not pass any callback function, array_filter() will remove all values equivalent to false in the array by default.
$data = [
'name' => 'John',
'age' => 0,
'email' => '',
'is_active' => false,
'preferences' => [],
'bio' => null,
'website' => 'https://m66.net/profile/john'
];
$filtered = array_filter($data);
print_r($filtered);
Array
(
[name] => John
[website] => https://m66.net/profile/john
)
As you can see, 0 , '' , false , null , [] are all filtered out, leaving only elements with boolean value true .
For example, if you want to remove only false and null and retain 0 and '' , you need to customize the callback function:
$filtered = array_filter($data, function ($value) {
return $value !== false && $value !== null;
});
print_r($filtered);
This allows for more precise control of filtering rules.