php · level 2 · unit 2 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
runs a function on every item for you.
Want every price with VAT added, or every name in capitals? array_map takes a function and an array, runs the function on each item, and gives back a new array of the answers. The function you hand over is a , because array_map calls it back once per item.
The quickest callback is an : fn($price) => $price * 2. It has no name. It takes a parameter and hands back whatever comes after =>, with no return needed.
Unlike the functions you wrote in Level 1, an arrow function can read the variables around it, like $rate here.
<?php
$prices = [10, 4, 25];
$rate = 1.2;
$with_vat = array_map(fn($price) => $price * $rate, $prices);
echo implode(", ", $with_vat) . "\n";
$names = ["ada", "grace"];
echo implode(" and ", array_map(fn($name) => strtoupper($name), $names)) . "\n"; In array_map, the callback goes first and the array second.
guess first
Turn the heat up. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
$temps = [20, 25, 30];
$hotter = array_map(fn($temp) => $temp + 5, $temps);
echo implode(", ", $temps) . "\n";
echo implode(", ", $hotter) . "\n";
your turn
Your turn. Run a bonus round.
Type what each score should turn into, using $score, for example $score * 10 or $score + 3. Then run it.
fix it
Nobody is shouting yet. Can you fix it?
- The TypeError says argument 1 must be a valid callback. What is in the first slot on line 3?
array_mapwants the callback first and the array second. These two are the wrong way round.- Swap them:
array_map(fn($name) => strtoupper($name) . "!", $names), then press run.
nailed it
one line changed a whole array. :D
array_mapruns a callback on every item.fn($x) => ...is a short function that hands back its answer.- The original array stays as it was.
new words in your collection
- callback
- arrow function
- array_map
This lesson isn’t saved. A free account remembers every lesson you finish.