What is the purpose of array_filter in PHP?
The array_filter function in PHP is used to filter elements in an array. It iterates through the array, passing each element to a callback function for evaluation. If the callback function returns true, the element is kept in the result array; otherwise, it is filtered out.
The array_filter function can be used to remove unwanted elements from an array or filter out the needed elements based on specific conditions. It is commonly used for filtering, cleaning, and selecting data.
The syntax of the array_filter function is as follows:
array_filter(array $array [, callable $callback [, int $flag = 0]]);
$array is the array to be filtered, $callback is an optional callback function used to evaluate each element in the array, $flag is an optional flag parameter used to set the behavior of the callback function.
If the $callback parameter is omitted, the array_filter function will remove all empty, false, and null values from the array. If the $callback parameter is provided, the callback function will accept array elements as parameters and return a boolean value to determine whether to keep that element. If the $flag parameter is set to ARRAY_FILTER_USE_KEY, the callback function will accept the key names of the array as parameters.
Here is an example demonstrating how to use the array_filter function to remove empty values from an array:
$array = [1, 2, null, 3, '', 4];
$result = array_filter($array);
print_r($result);
The output result is:
Array
(
[0] => 1
[1] => 2
[3] => 3
[5] => 4
)
Empty values have been removed, leaving only non-empty elements.