PHP array_filter() Function
PHP array_filter() Syntax
array_filter(array $array, ?callable $callback = null, int $mode = 0): array
PHP array_filter() Basic examples
$nums = [1,2,3,4];
$even = array_filter($nums, fn($n) => $n % 2 === 0);
var_dump($even);
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);
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]));
array(1) {
[3]=> int(5)
}
Falsy values are removed by default.
PHP array_filter() Common mistakes
Expecting reindexed keys
array_filter preserves original keys.
array_filter([10,20,30]);
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
-
array_allLearn more about array_all
-
array_anyLearn more about array_any
-
array_change_key_caseLearn more about array_change_key_case
-
array_chunkLearn more about array_chunk
-
array_map PHP examplesLearn more about array_map PHP examples
-
array_reduce PHP examplesLearn more about array_reduce PHP examples