Example 1 — Keeping Even Numbers
Write a callback that returns true for the items you want to keep.
<?php
$numbers = [1, 2, 3, 4, 5, 6];
$even = array_filter($numbers, fn($n) => $n % 2 === 0);
print_r($even); How It Works
- The callback is called once for every number.
- It returns true when the number divided by 2 leaves a remainder of 0.
- The numbers 2, 4 and 6 pass the test and are kept.
- Their original keys 1, 3 and 5 are preserved in the result.

