Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

array_filter

Keeps the array elements that pass a test.

Available since: PHP 4

Syntax

array_filter(array $array, ?callable $callback = null, int $mode = 0): array

Parameters

ParameterTypeDescription
$arrayarrayThe source array.
$callback?callableA test function: an element stays if it returns `true`. Without it, empty values are removed.
$modeintWith `ARRAY_FILTER_USE_KEY` the function receives the key, with `ARRAY_FILTER_USE_BOTH` the value and the key.

Return value

arrayA new array with the selected elements. Keys are preserved.

Examples

Even numbers only — note the keys:

<?php
 
print_r(array_filter([1, 2, 3, 4], fn ($n) => $n % 2 === 0));

Output:

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

Without a function, empty values are removed:

<?php
 
print_r(array_filter([0, 1, '', 'a', null]));

Output:

Array
(
    [1] => 1
    [3] => a
)

To get sequential keys, pass the result through array_values():

<?php
 
print_r(array_values(array_filter([1, 2, 3, 4], fn ($n) => $n % 2 === 0)));

Output:

Array
(
    [0] => 2
    [1] => 4
)

Notes

The original keys are preserved, so the result may have gaps in its numbering. Add array_values() when you need a plain list.

See also

  • array_map — Applies a function to every element of an array.
  • array_unique — Removes duplicate values from an array.

Related recipes

In the tutorial

  • Functions — How to declare and call functions in PHP — parameters, return values, types and scope.

Thanks for reading!

Donate to the site — we work hard for you.