In PHP, array_filter() is a very practical function that can remove "empty" values from an array, or use callback functions to perform complex filtering. However, it is not the best choice in all scenarios. In some cases, using array_filter() can cause performance issues, confusing code logic, and even errors in the results. Let's discuss under what circumstances we should avoid using array_filter() .
array_filter() will retain the key names of the original array by default, but will not be reindexed. If you expect an index array that increments continuously from 0, using array_filter() may disappoint you. For example:
$data = [0 => 'A', 1 => '', 2 => 'B'];
$result = array_filter($data);
print_r($result);
The output is:
Array
(
[0] => A
[2] => B
)
If you try to pass it to the front end with json_encode at this time, or access elements with indexes, it may cause problems. At this point you should use array_values(array_filter(...)) or consider using foreach to handle it yourself.
array_filter() will remove all "false values" by default (false, 0, null, '', [], etc.), which will destroy data integrity in some scenarios. For example:
$data = [0, 1, 2, false];
$result = array_filter($data);
print_r($result);
The output is:
Array
(
[1] => 1
[2] => 2
)
Both false and 0 are removed, but if these values make sense to you, for example, you are counting the user's vote (0 means objection), this becomes unacceptable.
The solution is to pass a custom callback function:
$result = array_filter($data, function($val) {
return $val !== null;
});
If you just want to remove null, don't rely on default behavior.
Although array_filter() is a convenience function, it is implemented by traversing the entire array, which may affect performance if you call frequently in a large data set, or in a high concurrency scenario. For example, repeated use of array_filter() on an array with millions of records will cause considerable performance overhead.
At this time, you should consider whether you really need to use it, or whether it can be merged into other processing processes, such as directly filtering unwanted values in SQL queries, rather than waiting for the result to come out before processing in PHP.
PHP is not a data processing language that naturally supports chain calls (unlike JavaScript's map/filter/reduce ), so using array_filter() in chain calls can easily cause logical confusion. For example: