In this post, you will learn how to filter the elements of an array by keys or values in PHP.
PHP array_filter() function
With the help of the PHP array_filter()
function, you can filter the values of an array using a callback function.
array_filter(array, callbackFunction, flag)
array
(Required) – The array whose elements you want to filter.callbackFunction
(Optional) – A callback function where you write the filter logic.flag
(Optional) – Flag determining what arguments are sent to callback:ARRAY_FILTER_USE_KEY
– pass key as the only argument tocallback
instead of the value.ARRAY_FILTER_USE_BOTH
– pass both value and key as arguments tocallback
instead of the value.
This array_filter
function returns a new array with the filtered values, and the keys of the values are preserved in the new array.
The callback function will iterate for each value of the array, and it returns true to keep the value into the new array, else return false.
<?php
// A list of users with their age
$usersWithAge = [
"Mark" => 24,
"John" => 32,
"Olive" => 14,
"Bruce" => 45,
"Teri" => 12,
"Clark" => 22,
"Aida" => 9,
];
// Above 18 or Equal
$adults = array_filter($usersWithAge, function($val){
return $val >= 18;
/** The following commented code is for beginners
* to understand what the above return statement is doing.
*
if($val >= 18){
return true;
}
return false;
*
*/
});
print_r($adults);
Array
(
[Mark] => 24
[John] => 32
[Bruce] => 45
[Clark] => 22
)
Example of array_filter() function with Flag
1. Access the keys inside the callback function
By default, you can access the array values, but by adding the ARRAY_FILTER_USE_KEY
flag you can access the keys.
<?php
// A list of users with their age
$usersWithAge = [
"Mark" => 24,
"John" => 32,
"Olive" => 14,
"Bruce" => 45,
"Teri" => 12,
"Clark" => 22,
"Aida" => 9,
];
$users = array_filter($usersWithAge, function($key){
echo "$key \n";
return true;
}, ARRAY_FILTER_USE_KEY);
Mark
John
Olive
Bruce
Teri
Clark
Aida
2. Access both values and keys inside the callback function
There is a flag called ARRAY_FILTER_USE_BOTH
to access both values and keys.
<?php
// A list of users with their age
$usersWithAge = [
"Mark" => 24,
"John" => 32,
"Olive" => 14,
"Bruce" => 45,
"Teri" => 12,
"Clark" => 22,
"Aida" => 9,
];
$users = array_filter($usersWithAge,function($value, $key){
echo "$key => $value \n";
return true;
}, ARRAY_FILTER_USE_BOTH);
Mark => 24
John => 32
Olive => 14
Bruce => 45
Teri => 12
Clark => 22
Aida => 9