×

php · level 2 · unit 2 · lesson 2

  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

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.