Current Location: Home> Latest Articles> Use array_filter() to filter elements with boolean value false

Use array_filter() to filter elements with boolean value false

M66 2025-06-05

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.

What is array_filter()?

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 .

grammar:

 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

Example: Remove element with boolean value false

When we do not pass any callback function, array_filter() will remove all values ​​equivalent to false in the array by default.

Sample code:

 $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);

Output result:

 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 .

What if you just want to filter out some "false values"?

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.