PHP array_filter() Function
The array_filter() function filters elements of an array using a callback function, returning only elements that pass the test.
Syntax
array_filter(
array $array,
?callable $callback = null,
int $mode = 0
): array
Parameters
| Parameter | Type | Description |
|---|---|---|
$array |
array | The array to filter |
$callback |
callable|null | The callback function. If null, removes falsy values. |
$mode |
int | ARRAY_FILTER_USE_KEY or ARRAY_FILTER_USE_BOTH |
Return Value
Returns a filtered array. Keys are preserved.
Try It Online
Output
Click Run to execute your code
More Examples
Remove Empty Values
<?php
$data = ["hello", "", "world", null, 0, false, "php"];
// Without callback - removes all falsy values
$filtered = array_filter($data);
print_r($filtered);
// ["hello", "world", "php"] (indices: 0, 2, 6)
?>
Filter with Callback
<?php
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Keep only even numbers
$even = array_filter($numbers, fn($n) => $n % 2 === 0);
print_r($even);
// [2, 4, 6, 8, 10]
?>
Filter by Key
<?php
$data = [
"name" => "John",
"email" => "[email protected]",
"password" => "secret",
"age" => 30
];
// Keep only specific keys
$allowed = ["name", "email", "age"];
$filtered = array_filter(
$data,
fn($key) => in_array($key, $allowed),
ARRAY_FILTER_USE_KEY
);
print_r($filtered);
?>
Note:
array_filter() preserves keys. Use array_values() to reindex if needed.
Common Use Cases
- Removing empty/null values from arrays
- Filtering user input
- Selecting items matching criteria
- Data validation and cleaning
Related Functions
- array_map() - Transform array elements
- array_values() - Reindex array
- in_array() - Check if value exists
Enjoying these tutorials?