Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

array_filter: selecting elements while preserving keys

array_filter keeps elements that satisfy a callback condition. Without a callback it removes values PHP considers empty, including the number 0 and the string "0".

Version: PHP 8.4

Syntax

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

By default, the callback receives a value. A result interpreted as true keeps the original element; it does not replace it with the callback result. To remove only null, use an explicit condition such as $value !== null.

Without a callback, removed values include 0, "0", "", false, null and an empty array. This is not universal data cleaning: zero may be a valid price or result. Choose a rule that matches the task.

Keys remain unchanged, so removing elements can leave gaps in a list. array_values recreates indexes starting at zero. This matters for JSON: an array with gaps can be encoded as an object instead of a list. The example shows a preserved index and separate normalization.

ARRAY_FILTER_USE_KEY passes only the key, while ARRAY_FILTER_USE_BOTH passes the value followed by the key. Do not add or remove elements of the filtered array inside the callback: the result of that modification is undefined.

Examples

<?php
declare(strict_types=1);

$values = [0, "0", "", null, false, 2];
echo json_encode(array_keys(array_filter($values)), JSON_THROW_ON_ERROR), "\n";
$notNull = array_filter($values, fn(mixed $value): bool => $value !== null);
echo json_encode(array_values($notNull), JSON_THROW_ON_ERROR), "\n";

Result

[5]
[0,"0","",false,2]

Sources