Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Array Functions

PHP array_filter() function

Reference for PHP array_filter(): keep elements that pass a test, filter by key or by value and key, and handle the falsy-value default and kept keys.

array_filter() returns a new array containing only the elements for which a callback returns a truthy value. Elements that fail the test are dropped.

Keys are preserved, so a filtered list usually has gaps in its numbering. Wrap the result in array_values() when you need a clean list again. Without a callback, the function removes every "falsy" value.

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

Try it

PHP Filtering by value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Modes: filter by key or by both

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
array_filter(array $array, ?callable $callback = null, int $mode = 0): array
Name Description
$array The array to filter. It is not modified.
$callback Returns true to keep the element. If null or omitted, every element that converts to false is removed.
$mode 0 (default): callback gets the value. ARRAY_FILTER_USE_KEY: callback gets the key. ARRAY_FILTER_USE_BOTH: callback gets the value and then the key.

Return value: an array of the kept elements, with their original keys.

Usage notes

  • Keys are preserved. Apply array_values() if you need sequential keys, especially before json_encode(), which would otherwise output an object.
  • Default filter is loose. Without a callback, 0, 0.0, "0", "", null, false and [] are all removed. A zero you wanted to keep disappears; write an explicit callback in that case.
  • The callback result is converted to bool, so returning a non-empty string keeps the element, which can hide mistakes.
  • Order of arguments in ARRAY_FILTER_USE_BOTH is value first, key second, which is the reverse of foreach ($a as $k => $v).
  • Transforming and filtering are separate steps: use array_map() to change values and array_filter() to drop some.
  • Removing duplicates is the job of array_unique().