PHP array_filter() Function

Quick summary: The PHP array_filter() function filters array elements using a callback.

PHP array_filter() Syntax

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

PHP array_filter() Basic examples

$nums = [1,2,3,4];
$even = array_filter($nums, fn($n) => $n % 2 === 0);
var_dump($even);
PHP
Output:
array(2) {
  [1]=> int(2)
  [3]=> int(4)
}

Keeps only elements that match the condition.

PHP array_filter() Real-world usage

$users = ['admin', '', 'editor'];
$valid = array_filter($users);
var_dump($valid);
PHP
Output:
array(2) {
  [0]=> string(5) "admin"
  [2]=> string(6) "editor"
}

Removes empty values.

PHP array_filter() Edge cases

var_dump(array_filter([0, false, null, 5]));
PHP
Output:
array(1) {
  [3]=> int(5)
}

Falsy values are removed by default.

PHP array_filter() Common mistakes

Expecting reindexed keys

array_filter preserves original keys.

Incorrect
array_filter([10,20,30]);
Correct
array_values(array_filter([10,20,30]));

Use array_values to reindex.

PHP array_filter() Frequently Asked Questions

What does array_filter() do in PHP?

array_filter() filters elements of an array using a callback function.

What is the syntax of array_filter()?

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

What happens if no callback is provided?

array_filter() removes all falsy values like false, null, 0, and empty strings.

Does array_filter() modify the original array?

No, it returns a new filtered array.

Are array keys preserved in array_filter()?

Yes, keys are preserved by default.

Can array_filter() reindex the array?

No, use array_values() to reindex the result.

What is the mode parameter in array_filter()?

It controls whether the callback receives values, keys, or both.

Is array_filter() faster than foreach?

Performance is similar; readability is usually the deciding factor.

Can array_filter() remove null values?

Yes, null values are removed when no callback is provided.

What is a real-world use case of array_filter()?

Filtering user input, removing empty values, or selecting items based on conditions.

Can array_filter() be combined with array_map()?

Yes, they are often used together for transforming and filtering data.

Does array_filter() support associative arrays?

Yes, it works with both indexed and associative arrays.

PHP array_filter() Related PHP Functions