array_filter

Filters an array with a callback, keeping only the elements for which the callback returns true.

Signature
array_filter(array $array, ?callable $callback = null, int $mode = 0): array
  • Added in PHP 4.0.6

Parameters

ParameterTypeDescription
$arrayarrayThe array to iterate over.
$callbackoptional?callable= nullCalled for each element; return true to keep the element. If null, every element that is loosely equal to false is removed.
$modeoptionalint= 0What gets passed to the callback: 0 for the value, ARRAY_FILTER_USE_KEY for the key, ARRAY_FILTER_USE_BOTH for value and key in that order.

Return value

arrayA new array containing only the elements that passed the test, with the original keys preserved.

Errors

Passing a non-callable value as $callback throws a TypeError.

Changelog

  • PHP 8.0.0$callback is nullable, so passing null explicitly is now allowed instead of omitting it.
  • PHP 8.0.0An E_WARNING is emitted if the callback expects a parameter by reference.

array_filter() walks an array and builds a new one from the elements your callback approves of. It is the standard way to express "give me only the rows that match" without writing a foreach and an accumulator.

The three modes

By default the callback receives only the value. Pass ARRAY_FILTER_USE_KEY to filter on keys instead — useful for whitelisting request fields — or ARRAY_FILTER_USE_BOTH to receive (value, key). Note that order: it is value first, key second, which is the reverse of what most people guess.

Calling it with no callback

Omitting the callback removes every element that is falsy: 0, 0.0, "", "0", null, false and []. That is broader than most people want. If you only meant to strip nulls, say so explicitly with fn($v) => $v !== null, otherwise a legitimate 0 or "0" quietly disappears.

Keys survive

The result keeps the original keys, so filtering [10, 20, 30] can produce keys 1 and 2 with no 0. That is fine for associative data and a problem for anything you intend to serialise as a JSON array.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Keep only the active records from a query result before rendering a list.
  • Whitelist incoming form fields by key so unexpected input never reaches your model.
  • Strip null values out of an options array before merging it over defaults.

Frequently asked questions

Does array_filter preserve keys?

Yes, it always preserves the original keys. If you need a sequentially numbered list back, pass the result through array_values().

What is the difference between array_filter and array_map?

array_filter decides which elements to keep and never changes their values; array_map transforms every value and never removes any. Use array_filter to shrink an array and array_map to rewrite it.

How do I remove only null values with array_filter?

Pass an explicit callback: array_filter($arr, fn($v) => $v !== null). Calling array_filter with no callback removes every falsy value, including 0, "0", false and empty arrays.

More examples

Reindex a filtered list for JSON

The filtered array keeps keys 1, 2 and 3, so json_encode writes an object. array_values() renumbers from zero and the same data encodes as a real JSON array. array_is_list() confirms the gap.

Example · php
<?php
$numbers = [10, 20, 30, 40];
$big = array_filter($numbers, fn($n) => $n > 15);

echo json_encode($big), "\n";
echo json_encode(array_values($big)), "\n";
var_dump(array_is_list($big));

Filter with both value and key

With ARRAY_FILTER_USE_BOTH the callback gets the value first and the key second. Here it keeps the db_ prefixed settings but drops db_user because its value is an empty string.

Example · php
<?php
$settings = ['db_host' => 'localhost', 'db_port' => 5432, 'app_name' => 'demo', 'db_user' => ''];

$db = array_filter(
    $settings,
    fn($value, $key) => str_starts_with($key, 'db_') && $value !== '',
    ARRAY_FILTER_USE_BOTH
);

print_r($db);

Discussion

  • Be the first to comment on this lesson.