Fixes & guides

PHP array_filter: keys, ARRAY_FILTER_USE_BOTH and re-indexing

How array_filter() decides what to keep, why it removes "0" without a callback, how to filter by key or by key and value, and why the result needs array_values() before you treat it as a list.

On this page
  1. Filtering by value
  2. Without a callback: removing “empty” values
  3. Re-indexing the result with array_values()
  4. Filtering by key: ARRAY_FILTER_USE_KEY
  5. Key and value: ARRAY_FILTER_USE_BOTH
  6. Filtering objects and nested arrays
  7. Filter, then map

array_filter() returns the elements for which a callback returns true. It never changes the original array, and it keeps the original keys, which is the source of its two classic bugs.

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

Filtering by value

$orders = [
    ['id' => 1, 'total' => 120, 'status' => 'paid'],
    ['id' => 2, 'total' => 15,  'status' => 'open'],
    ['id' => 3, 'total' => 80,  'status' => 'paid'],
];

$paid = array_filter($orders, fn (array $o) => $o['status'] === 'paid');
// [0 => [...id 1], 2 => [...id 3]]   note the keys: 0 and 2

The callback receives each value and should return a boolean. Anything truthy keeps the element.

Without a callback: removing “empty” values

With no callback, array_filter() removes every value that is falsy in PHP:

array_filter([0, 1, '', 'a', null, false, '0', [], 0.0, ' ']);
// [1 => 1, 3 => 'a', 9 => ' ']

That includes 0, '0' and 0.0, which are often real data: a quantity of zero, a “0” checkbox value, a zero balance. If you only want to drop null or empty strings, say so:

array_filter($values, fn ($v) => $v !== null);              // remove nulls only
array_filter($values, fn ($v) => $v !== null && $v !== ''); // remove nulls and empty strings
array_filter($values, strlen(...));                         // keep non-empty strings, including "0"

The last form only works for arrays of strings; strlen(null) is deprecated since PHP 8.1.

Re-indexing the result with array_values()

Because keys are preserved, a filtered list can have gaps:

$names = array_filter(['Ana', '', 'Chen']);   // [0 => 'Ana', 2 => 'Chen']

$names[1];                    // Warning: Undefined array key 1
json_encode($names);          // {"0":"Ana","2":"Chen"}   an object, not a list
count($names);                // 2, so for ($i = 0; $i < count($names); $i++) misses Chen

Wrap the call in array_values() whenever the result is a list:

$names = array_values(array_filter(['Ana', '', 'Chen']));   // ['Ana', 'Chen']

The JSON case is the one that breaks front ends. An API that returned [...] yesterday returns {...} today because one item was filtered out. PHP array to JSON covers that in detail. On PHP 8.1+, array_is_list() tells you whether an array is a clean list.

If the keys are meaningful, such as IDs, keep them and skip array_values().

Filtering by key: ARRAY_FILTER_USE_KEY

The third argument changes what the callback receives. With ARRAY_FILTER_USE_KEY, it gets only the key:

$input = ['name' => 'Ana', 'email' => '[email protected]', 'is_admin' => '1'];
$allowed = ['name', 'email'];

$safe = array_filter($input, fn (string $key) => in_array($key, $allowed, true), ARRAY_FILTER_USE_KEY);
// ['name' => 'Ana', 'email' => '[email protected]']

For a fixed allowlist like this, array_intersect_key($input, array_flip($allowed)) does the same thing without a callback.

Key and value: ARRAY_FILTER_USE_BOTH

With ARRAY_FILTER_USE_BOTH, the callback receives the value first, then the key:

$stock = ['apples' => 12, 'pears' => 0, 'plums' => 4, '_total' => 16];

$available = array_filter(
    $stock,
    fn (int $qty, string $item) => $qty > 0 && !str_starts_with($item, '_'),
    ARRAY_FILTER_USE_BOTH,
);
// ['apples' => 12, 'plums' => 4]

Swapping the parameter order is an easy mistake and usually fails silently, so give the parameters types: a TypeError is better than a wrong result.

Filtering objects and nested arrays

The callback can use anything it can reach, including methods and outer variables:

$active = array_filter($users, fn (User $u) => $u->isActive() && $u->lastLogin > $cutoff);

array_filter() works one level deep. To clean a nested structure, recurse:

function filterRecursive(array $data): array
{
    foreach ($data as $key => $value) {
        if (is_array($value)) {
            $data[$key] = filterRecursive($value);
        }
    }
    return array_filter($data, fn ($v) => $v !== null && $v !== []);
}

Filter, then map

array_filter() and array_map() chain naturally. Filter first so the map does less work:

$emails = array_values(array_map(
    fn (User $u) => $u->email,
    array_filter($users, fn (User $u) => $u->subscribed),
));

If you only need to know whether any or all elements match, PHP 8.4 added array_any() and array_all(), which stop at the first decisive element. array_find() returns the first matching value. For a single membership check, see in_array, and for transforming values, array_map.

Found a mistake or something out of date? Tell us and we will fix it. See our editorial policy.

A good place to start

What are you working on?

Tools, guides, PHP versions and the archive.

ToolJSON ↔ PHP arrayConvert JSON to a PHP array literal with short or array() syntax, or turn a PHP array back into JSON. Runs in your browser; nothing is uploaded.ToolSerialize / unserializeRead PHP serialized strings as a tree, repair wrong string lengths after a search-and-replace, or serialize a PHP array or JSON. Parsed safely in your browser.ToolComposer constraint testerSee exactly which versions a Composer constraint such as ^2.1, ~1.4 or >=8.1 <8.4 allows, in plain English, and test versions against it.ToolPHP date() format builderBuild a PHP date() or DateTime::format() string with a live preview in any time zone, plus a reference for every format character.ToolBcrypt generatorGenerate a bcrypt hash with a cost slider and verify a password against an existing hash. Output matches PHP password_hash() and password_verify(). Runs in your browser.ToolPHP version checkerPaste PHP code and see the minimum version it needs, the line that decided it, and any removed functions that cap the newest version it can run on.ToolCrontab generatorBuild a cron expression with presets, read it in plain English, see the next run times, and copy the crontab line or the matching Laravel scheduler call.ToolPHP upgrade checklistPick your current and target PHP versions and get every breaking change, deprecation and tooling step in between, as a checklist you can copy.GuideAllowed memory size exhaustedWhat PHP's memory_limit fatal error means, how to tell a real leak from a big job, and fixes for the usual causes: loading whole tables, unbounded arrays, Composer and recursion.GuideComposer dependency conflictsA step-by-step way to read Composer's conflict output, find the package that is blocking you, and fix it without --ignore-platform-reqs or deleting the lock file.Guidecomposer install vs updatecomposer install reproduces composer.lock; composer update rewrites it. Here is what each command does, when to use which, and a safe production deploy routine.GuideComposer uses the wrong PHP versionComposer says "your php version (8.1.x) does not satisfy that requirement" when your server runs 8.3? The cause is usually the CLI binary, config.platform.php, or platform_check.php.GuideEloquent N+1 queriesHow to spot N+1 queries in Laravel, fix them with eager loading, withCount() and constrained loads, and make Laravel throw an exception the next time one slips in.GuideHeaders already sentThe warning names the file and line that produced output. Here is how to read it, the five usual culprits (BOM, whitespace, echo, warnings, closing tags) and fixes that do not just hide it.GuideWriting a talk proposalWhat reviewers look for in a call-for-papers submission: a specific title, an abstract for attendees, notes for the committee, and a talk-sized idea. With a worked example and a checklist.GuideLaravel queue jobs not runningJobs dispatched but never processed, stuck in the jobs table, or running old code? Work through the connection, the queue name, the worker, failed jobs and deploy restarts.PHP versionsWhat's new in PHP 8.4PHP 8.4 (released 21 November 2024) brought property hooks, public private(set) visibility, new without parentheses, lazy objects, an HTML5 DOM parser and array_find(). Plus the deprecations that matter.PHP versionsWhat's new in PHP 8.5PHP 8.5 (released 20 November 2025) added the |> pipe operator, a standards-compliant URI extension, clone() with property overrides, #[\NoDiscard] and array_first()/array_last().PHP versionsWhat's new in PHP 8.6PHP 8.6 was released on 19 November 2026. Partial function application, clamp(), readonly property defaults, Io\Poll and Time\Duration, plus the session and ValueError changes to check before upgrading.GuidePHP array_filterHow array_filter() decides what to keep, why it removes "0" without a callback, how to filter by key or by key and value, and why the result needs array_values() before you treat it as a list.GuidePHP array_mapHow array_map() treats keys, how to map with the key as well as the value, what happens with several arrays or a null callback, and when a plain foreach or array_walk() is the better choice.GuidePHP array to JSONWhy json_encode() sometimes gives you an object instead of a list, how to keep floats and slashes intact, and how to catch the silent false that malformed UTF-8 returns.GuidePHP array to stringThree ways to turn a PHP array into a string, and when to use each: implode() for display and CSV-like lists, json_encode() for APIs and storage, serialize() for PHP-only data. Plus the Array to string conversion warning.GuidePHP FibersPHP 8.1 Fibers let a function pause and resume without returning. Here is how start, suspend and resume pass values, how Fibers differ from generators and threads, and where they help in real code.GuidePHP in_arrayWhy in_array() can return true for values that are not in the array, what changed in PHP 8, when to pass strict = true, and how to replace slow in_array() calls with isset() lookups.GuideInterface vs abstract classInterfaces define what a class can do; abstract classes share how it is done. A side-by-side table, examples of each, the common pattern of using both, and what PHP 8.1 to 8.4 changed for interfaces.GuidePHP sort arrayWhich PHP sort function to use, in one table: by value or key, keep keys or not, ascending or descending, or with your own comparison. Plus sorting by a column, by several fields and naturally.GuideDuplicate webhooks in PHPWebhook providers retry, so the same event can arrive twice. Verify the signature, record the event ID with a unique key, answer fast and process in a queue: a pattern that works in plain PHP, Laravel and Symfony.GuidePHPStan baseline for legacy codeGenerate a PHPStan baseline, stop new errors from getting in, then raise the level step by step. A tested routine for old PHP codebases.GuidePSR-4 autoloadingHow PSR-4 maps namespaces to folders, how to configure it in composer.json, and why "Class not found" happens: case, typos, a stale autoloader or a namespace that does not match the path.GuideSerialized data broken after search-replaceChanging a domain name with SQL REPLACE() or sed corrupts PHP serialized strings because their byte lengths no longer match. Here is how to spot it and repair it safely.GuideUpgrade PHP with RectorUpgrade a PHP application one version at a time: pin the baseline, let Rector rewrite syntax, let PHPStan find what Rector cannot, and prove it with tests before you switch runtimes.PHP versionsSupported PHP versionsRelease, active support and end-of-life dates for every PHP version.ArchiveSunshinePHP talk archive 2013–2020Talk titles and speakers from eight years of the Miami PHP conference.ArchiveSpeaker indexEveryone who spoke at SunshinePHP, A to Z.