How to Use array_filter in PHP: Syntax and Examples
In PHP,
array_filter is used to filter elements of an array using a callback function that returns true for elements to keep. If no callback is provided, it removes all falsy values like false, 0, or empty strings from the array.Syntax
The array_filter function takes an array and an optional callback function. It returns a new array containing only the elements for which the callback returns true.
- array: The input array to filter.
- callback (optional): A function that receives each element and returns
trueto keep it orfalseto remove it. - mode (optional): Controls whether to pass keys or values to the callback (default is values).
php
array_filter(array $array, ?callable $callback = null, int $mode = 0): array
Example
This example shows how to use array_filter to keep only even numbers from an array.
php
<?php $numbers = [1, 2, 3, 4, 5, 6]; $evenNumbers = array_filter($numbers, fn($num) => $num % 2 === 0); print_r($evenNumbers); ?>
Output
Array
(
[1] => 2
[3] => 4
[5] => 6
)
Common Pitfalls
One common mistake is expecting array_filter to reindex the filtered array. It preserves original keys, which can cause issues if you expect sequential keys.
Another pitfall is forgetting that if no callback is given, array_filter removes all falsy values like false, 0, '', and null.
php
<?php // Wrong: expecting keys to be reindexed $filtered = array_filter([0 => 'a', 1 => 'b', 2 => ''], fn($v) => $v !== ''); print_r($filtered); // Right: reindex with array_values $filtered = array_values(array_filter([0 => 'a', 1 => 'b', 2 => ''], fn($v) => $v !== '')); print_r($filtered); ?>
Output
Array
(
[0] => a
[1] => b
)
Array
(
[0] => a
[1] => b
)
Quick Reference
| Parameter | Description |
|---|---|
| array | The input array to filter |
| callback | Function to test each element; returns true to keep element |
| mode | Flag to pass keys or values to callback (default is values) |
Key Takeaways
Use array_filter to keep array elements that meet a condition defined by a callback.
If no callback is given, array_filter removes all falsy values from the array.
array_filter preserves original keys; use array_values to reindex if needed.
The callback function should return true to keep an element, false to remove it.
array_filter is useful for cleaning or selecting specific data from arrays easily.