array_filter() Function Use in PHP

array_filter() is a built in PHP function that creates a new array containing only the elements that pass a test. It takes an array and, optionally, a callback function. The callback receives each value (and, if requested, its key) and returns true to keep the element or false to remove it.

Version Support: array_filter() in PHP 8.5, array_filter() in PHP 8.4, array_filter() in PHP 8.3, array_filter() in PHP 8.2, array_filter() in PHP 8.1, array_filter() in PHP 7.1, array_filter() in PHP 7.2, array_filter() in PHP 7.3, array_filter() in PHP 7.4

Example: Keep even numbers

<?php
$numbers = [1, 2, 3, 4, 5, 6];

$evenNumbers = array_filter($numbers, function ($number) {
   return $number % 2 === 0;
});

print_r($evenNumbers);
?>

Output:

Array
(
   [1] => 2
   [3] => 4
   [5] => 6
)

By default, array_filter() preserves the original keys. To reindex the results, use array_values():

$evenNumbers = array_values($evenNumbers);
// Result: [2, 4, 6]

You can also pass the key to the callback:

$prices = ["apple" => 2, "bread" => 0, "milk" => 3];

$nonZeroPrices = array_filter(
   $prices,
   fn($price, $item) => $price > 0,
   ARRAY_FILTER_USE_BOTH
);

Using ARRAY_FILTER_USE_BOTH provides both the value and key. Use ARRAY_FILTER_USE_KEY when the callback should receive only keys.

16 Views