×

php · level 2 · unit 2 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

keeps only the items that pass a test.

array_filter works like a sieve. Hand it an array and a callback that answers yes or no, and it gives back a new array of only the items where the callback said true. Notice the order: the array first, then the callback.

The kept items keep their old keys. Filter [4, 9, 7] for items over 5 and you get 9 at key 1 and 7 at key 2. There is no key 0 any more.

To number them from 0 again, wrap the result in . Then [0] is the first kept item.

<?php
$ages = [4, 9, 15, 7, 12];
$older = array_filter($ages, fn($age) => $age >= 8);
echo count($older) . " can ride: " . implode(", ", $older) . "\n";
$riders = array_values($older);
echo "First in the queue is " . $riders[0] . " years old\n";

array_filter keeps the items themselves, while array_map swaps each item for a new answer.