In PHP, array_filter() is a very common array processing function that is used to filter elements in an array. The array_filter() function can accept two parameters, the first parameter is an array, and the second is a callback function (optional). If no callback function is provided, the default behavior is used.
array_filter(array $array, callable $callback = null, int $mode = 0): array
$array : pending array.
$callback : A callback function for each array element. The callback function must return true or false to determine whether the element is retained.
$mode : Optional parameter to specify the filtering method, the default value is 0 .
When no callback function is provided, array_filter() uses the default behavior.
If array_filter() does not receive a callback function, it will automatically use a default filtering behavior: delete all "false values" in the array. In PHP, "false values" include the following:
false
null
0 (integer 0)
0.0 (floating point number 0)
'' (empty string)
'0' (String '0')
Empty array
Any of these false values will be removed from the array, and only those elements considered true values will be retained.
Suppose you have an array like this:
$array = [0, 1, false, 2, null, 3, '', '0', 4];
If we call array_filter() without passing in the callback function:
$result = array_filter($array);
print_r($result);
The output will be:
Array
(
[1] => 1
[3] => 2
[5] => 3
[8] => 4
)
As you can see, all "false values" have been removed, and only valid elements are left in the array.
This default behavior is very useful, especially when dealing with arrays that need to remove invalid data. For example, suppose you get some data from a user form, which may contain null values, 0, or null . Use array_filter() default behavior to quickly clear these invalid data and retain valid values.
When array_filter() does not provide a callback function, it will remove "false values" from the array by default.
This default behavior can help developers easily filter out unnecessary data, especially when handling incomplete or invalid input.
Other notes:
If you want to filter arrays based on custom rules, you can pass in a callback function instead of relying on the default behavior.
You can also use the ARRAY_FILTER_USE_KEY or ARRAY_FILTER_USE_BOTH parameters to access the keys and values of the array in the callback function at the same time.