PHP array_filter() Function
array_filter() returns the elements of an array that pass a callback condition.
Filter with a Callback
$numbers = [3, 8, 11, 14, 17];
$even = array_filter(
$numbers,
fn (int $number): bool => $number % 2 === 0
);
The original keys are preserved, so the resulting keys may not be consecutive.
Reindex the Result
Use array_values() when a zero-based list is needed, such as when returning a JSON array.
$even = array_values($even);
Filter Empty Values
If no callback is provided, array_filter() removes values PHP considers empty. This can remove values such as 0, "0", false, and an empty string. Use an explicit callback when those values may be meaningful.
Summary
array_filter() is a concise way to select values. Remember that keys are preserved and that the default empty-value behavior may be broader than intended.