The array_filter()
function in PHP is used to filter elements of an array using a callback function. It iterates over each element in the array and passes it to the callback function. If the callback returns true
, the element is included in the resulting array; otherwise, it is excluded.
🔧 Syntax:
array_filter(array $array, ?callable $callback = null, int $mode = 0): array
- $array: The input array.
- $callback (optional): A function to use for filtering. If no callback is provided, all falsey values (like
false
, 0
, null
, ''
, etc.) will be removed.
- $mode (optional): Can be
ARRAY_FILTER_USE_KEY
, ARRAY_FILTER_USE_BOTH
, or 0
(default: only value is passed).
✅ Example 1: Remove falsey values from array
$data = [0, 1, false, 2, '', 3, null, 'hello'];
$result = array_filter($data);
print_r($result);
🟢 Output:
Array
(
[1] => 1
[3] => 2
[5] => 3
[7] => hello
)
By default, array_filter
removes values like false
, 0
, ''
, null
.
✅ Example 2: Use custom callback to filter even numbers
$numbers = [1, 2, 3, 4, 5, 6];
$result = array_filter($numbers, function($num) {
return $num % 2 == 0; // keep even numbers
});
print_r($result);
🟢 Output:
Array
(
[1] => 2
[3] => 4
[5] => 6
)
✅ Example 3: Filter associative array using keys and values
$students = [
'john' => 75,
'jane' => 85,
'doe' => 50,
'smith' => 90
];
$result = array_filter($students, function($score, $name) {
return $score >= 80;
}, ARRAY_FILTER_USE_BOTH);
print_r($result);
🟢 Output:
Array
(
[jane] => 85
[smith] => 90
)
⚠️ Notes:
- The keys are preserved in the output.
- If you want to reindex the result, use
array_values()
on the result.