array_filter in php
The
array_filter() function in PHP is used to filter elements of an array based on a callback function. It iterates over each value in the input array, passes it to the callback function, and includes the element in the result array if the callback function returns true.
Syntax:
array array_filter(array $array, callable $callback = null, int $flag = 0)
Parameters:
$array(required): The input array to be filtered.$callback(optional): A callable function that defines the condition for filtering. If omitted, all entries of the array that evaluate toFALSEwill be removed.
$flag (optional): An integer value that specifies additional behavior for the callback function.
ARRAY_FILTER_USE_KEY: Passes the key as the only argument to the callback.
ARRAY_FILTER_USE_BOTH: Passes both the value and the key as arguments to the callback.
How it works:
The
array_filter() function iterates through each element of the $array. For each element, it calls the $callback function, passing the element's value (and optionally its key, depending on the $flag) as arguments. If the $callback function returns true, the element is included in the new array returned by array_filter(). If false is returned, the element is excluded. Array keys are preserved in the filtered array.Example:
<?php
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Filter out odd numbers (keep even numbers)
$even_numbers = array_filter($numbers, function($number) {
return $number % 2 === 0;
});
print_r($even_numbers);
// Output:
// Array
// (
// [1] => 2
// [3] => 4
// [5] => 6
// [7] => 8
// [9] => 10
// )
$data = [
'name' => 'John Doe',
'email' => '',
'age' => 30,
'city' => null
];
// Filter out empty or null values
$filtered_data = array_filter($data);
print_r($filtered_data);
// Output:
// Array
// (
// [name] => John Doe
// [age] => 30
// )
?>