How to filter a associative array in PHP

1 Answer

0 votes
$arr = [
    "a" => 1,
    "b" => 2,
    "c" => 3,
    "d" => 4,
    "e" => 5
];

$filteredArr = array_filter($arr, function ($value, $key) {
    return $value > 2; // Include only values greater than 2
}, ARRAY_FILTER_USE_BOTH);

print_r($filteredArr);




/*
run:

Array
(
    [c] => 3
    [d] => 4
    [e] => 5
)

*/

 



answered Aug 7, 2025 by avibootz
...