November 30, 2022 | Posted in PHP
The array_filter() function is a PHP built-in function introduced in PHP 4. This PHP function is handy for filtering the array elements using a user-defined callback function.
By iterating over the array values, the array_filter() function passes them to the callback function. The callback function is user-defined. If the callback function returns true, then the current value of the array is returned to the result array.
array array_filter($array, $callback_function, $flag)
The array_filter() function takes three parameters
$array: This refers to the input array, and it is required.
$callback_function(Optional): This parameter refers to the user-defined function. This callback function does all the logic to filter the input array. If no function is given, all the array entries are equal to false.
$flag(optional): Two filters can be used to perform the filter. ARRAY_FILTER_USE_KEY – which only passes the input array’s key to the callback function. ARRAY_FILTER_USE_BOTH – this flag indicates that the callback function will have both the key and value.
<?php
# Old School way
$numbers = [2, 3, 4, 89, 101, 5,200];
function evenn($numbers)
{
if ($numbers % 2 === 0)
return true;
}
print_r(array_filter($numbers, 'evenn'));
# The best approach with the arrow function
# only two line of code
$even_numbers = array_filter($numbers, fn($num) => $num % 2 == 0);
print_r($even_numbers);
<?php
/**
* Assume we have an array of people and
* want to filter out everyone who is older than 60 years old.
*/
$people = [
[
'name' => 'Anna',
'age' => 78
],
[
'name' => 'Maxi',
'age' => 40
],
[
'name' => 'Johna',
'age' => 65
],
[
'name' => 'Donald',
'age' => 59
],
[
'name' => 'Monir',
'age' => 37
]
];
$people_over_60 = array_filter($people, fn($person)=> $person['age'] > 60, ARRAY_FILTER_USE_BOTH );
print_r($people_over_60);
#Output
Array
(
[0] => Array
(
[name] => Anna
[age] => 78
)
[2] => Array
(
[name] => Johna
[age] => 65
)
)
<?php
$people = ["Johnny", "Timmy", "Bobby", "Sam", "Tammy", "Danny", "Joe"];
$names_end_with_y = array_filter($people, fn($person) => substr($person, -1 ) === 'y' );
print_r($names_end_with_y);
#Output
Array
(
[0] => Johnny
[1] => Timmy
[2] => Bobby
[4] => Tammy
[5] => Danny
)