PHP 8 reference · Array Functions

PHP array_filter() Function

Keep only the elements for which a callback returns true. Without a callback it removes empty values; keys are kept.

PHP 8 Since 4.0

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

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

Parameters

ParameterDescription
array The input array.
callback optional Returns true to keep an element. Without one, falsy values (0, "", null, false, []) are removed.
mode optional ARRAY_FILTER_USE_KEY passes the key, ARRAY_FILTER_USE_BOTH passes value and key. Default: 0

Return value

The filtered array, with the original keys.

Examples

Keep even numbersTry it yourself
<?php
$numbers = [1, 2, 3, 4, 5, 6];
print_r(array_filter($numbers, fn($n) => $n % 2 === 0));

Output

Array
(
    [1] => 2
    [3] => 4
    [5] => 6
)
Remove empty values and renumberTry it yourself
<?php
print_r(array_values(array_filter(["a", "", null, "b", 0, "0"])));

Output

Array
(
    [0] => a
    [1] => b
)
Filter by keyTry it yourself
<?php
$env = ["APP_NAME" => "camel", "DB_HOST" => "localhost", "APP_DEBUG" => "1"];
print_r(array_filter($env, fn($k) => str_starts_with($k, "APP_"), ARRAY_FILTER_USE_KEY));

Output

Array
(
    [APP_NAME] => camel
    [APP_DEBUG] => 1
)

Common mistakes

  • Keys are preserved, so the result can have gaps ([1 => …, 3 => …]) and turns into a JSON object. Wrap it in array_values() for a plain list.
  • Without a callback the string "0" is removed too, because it's falsy.

Version history

VersionChange
PHP 4.0Added
PHP 5.6Added the mode parameter.

In other languages

Was this page helpful?