Summary - Closures and callbacks
Build a functional filter/map chain with closures, arrow functions and callables.
Summary - Closures and callbacks
In this group you learned the six pillars of closures: the function () {} anonymous function, capturing variables with use ($x), the fn() => arrow function, the callable type, higher-order functions and binding with bindTo.
Combined, they let you write concise code that pipes data: array_filter filters, array_map transforms, closures carry outer variables inside.
The final task puts these three together in one chain.
Exercise Summary - Filter and add VAT chain
$prices = [100, 250, 50, 400] is given. First filter the prices greater than 100 with array_filter; then multiply each by 1.18 with array_map and fn (add VAT). Finally print each price on a new line.
Show example solution
Filter with $filtered = array_filter($prices, fn($p) => $p > 100);. Add VAT with $withTax = array_map(fn($p) => $p * 1.18, $filtered);. Print with foreach ($withTax as $price) { echo $price . "\n"; }.
Example solution:
<?php
// Filter prices and add VAT
$prices = [100, 250, 50, 400];
$filtered = array_filter($prices, fn($p) => $p > 100);
$withTax = array_map(fn($p) => $p * 1.18, $filtered);
foreach ($withTax as $price) {
echo $price . "\n";
}
Test yourself
-
Match the six pillars of the group
- function () {}
- Anonymous function
- use ($x)
- Captures a variable
- fn($n) => $n * 2
- Arrow function
- callable
- Type declaration
- bindTo()
- Binds $this
-
What is the shortest way to double every element of an array?
- A manual foreach loop
- Adding with array_push
- array_map with an arrow function
- Rewriting with a for loop
Show answer
array_map with an arrow function — Correct. array_map(fn($n) => $n * 2, $arr) doubles every element in one line.
-
Filter even numbers with array_filter
<?php $nums = [1, 2, 3, 4, 5]; $evens = array_filter($nums, ____); foreach ($evens as $n) { echo $n . "\n"; }Show answer
<?php $nums = [1, 2, 3, 4, 5]; $evens = array_filter($nums, fn($n) => $n % 2 === 0); foreach ($evens as $n) { echo $n . "\n"; }