Why are elements with a value of 0 deleted when using array_filter() in PHP?
In PHP, the array_filter() function is used to filter elements in an array and determine whether to retain the element according to the specified callback function. If no callback function is specified, array_filter() will use the default callback function to filter the array, which will delete elements considered "false values". "False values" in PHP include: false , null , 0 , "" (empty string), array() (empty array), and 0.0 .
Therefore, when you use array_filter() in PHP, if the element value in the array is 0 , it will be considered a false value and will be deleted. To better understand this problem, we can use a concrete example to show the behavior of array_filter() .
<?php
$array = [0, 1, 2, 3, 0, 4, 5, 0];
$filtered = array_filter($array);
print_r($filtered);
?>
Output:
Array
(
[1] => 1
[2] => 2
[3] => 3
[5] => 4
[6] => 5
)
In the above code, we create an array containing multiple integers, containing several 0 elements. When we use array_filter() , all elements with a value of 0 are deleted because 0 is considered a false value.
This is because the default behavior of the array_filter() function is to remove all elements considered "false values" from the array. PHP's type conversion rules determine that 0 is a false value. Specifically, 0 is converted to false , and false causes array_filter() to delete the element.
If you want to keep elements with a value of 0 , you can do this by providing a custom callback function. For example:
<?php
$array = [0, 1, 2, 3, 0, 4, 5, 0];
$filtered = array_filter($array, function($value) {
return $value === 0 || $value > 0;
});
print_r($filtered);
?>
Output:
Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[5] => 4
[6] => 5
[7] => 0
)
In this example, we use a custom callback function to ensure that the element with a value of 0 is retained, while the other elements are filtered according to our logic.
When using array_filter() , elements with a value of 0 are deleted because PHP treats 0 as a false value. In the absence of a callback function, array_filter() will automatically delete these false values. If you need to keep 0 or other specific values, you can provide a custom callback function to control the filtering behavior.