php · level 2 · unit 2 · lesson 3
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Pick out the passes. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
$marks = [55, 80, 40, 90];
$passes = array_filter($marks, fn($mark) => $mark >= 50);
echo $passes[0] . "\n";
echo $passes[2] . "\n";
your turn
Your turn. Pick films that fit your evening.
Type how many minutes you have for a film, like 100. Run it to see which films fit.
fix it
The second name in the queue is Bo. Can you fix it?
- Read the error:
Undefined array key 1. Which keys did Ann and Bo keep after the filter? - Ann kept key 0 and Bo kept key 2. Renumber the kept items from 0 before you read them.
- Wrap the filter in
array_values( ... )on line 3, then press run.
nailed it
you sifted out exactly what you wanted. :D
array_filterkeeps items where the callback saystrue.- Kept items keep their old keys.
array_valuesnumbers them from 0 again.
new words in your collection
- array_filter
- array_values
This lesson isn’t saved. A free account remembers every lesson you finish.