🎓 A1Learner
🔍
0 of 38 lessons completed

Array Callbacks

A callback is a function handed to another function so it can run on each value. Array callbacks let one array function do a job on every value in an array.

A named function maps each value

A foreach loop doubles each number by hand first. array_map with the named function doubleIt then does the same job in one line, and the two arrays print the same.

<?php
function doubleIt($n) {
  return $n * 2;
}
$nums = [1, 2, 3];
$byHand = [];
foreach ($nums as $n) {
  $byHand[] = $n * 2;
}
print_r($byHand);
$mapped = array_map("doubleIt", $nums);
print_r($mapped);

A closure keeps the passing scores

A closure is a function with no name, written inside the call. This closure returns true for a score of 60 or more, and array_filter keeps those scores with their keys.

<?php
$scores = [45, 82, 67, 30, 91];
$passed = array_filter($scores, function ($s) {
  return $s >= 60;
});
print_r($passed);

An arrow function maps and reduce totals

An arrow function is a short closure built with fn and an arrow sign. The map triples each number, and array_reduce adds the numbers into one total.

<?php
$nums = [1, 2, 3];
$tripled = array_map(fn($n) => $n * 3, $nums);
print_r($tripled);
$total = array_reduce($nums, fn($carry, $n) => $carry + $n, 0);
echo $total . "\n";

Example

<?php
$prices = [50, 100, 20, 10];
$withTax = array_map(fn($p) => $p + $p / 5, $prices);
print_r($withTax);
$big = array_filter($withTax, fn($p) => $p >= 24);
print_r($big);
$total = array_reduce($big, fn($carry, $p) => $carry + $p, 0);
echo "Total: " . $total . "\n";

Key points

  • array_map runs a callback on each value and returns a new array.
  • array_filter returns a new array with the values the callback accepted.
  • array_reduce combines an array into one value step by step.
  • A closure is a function written inside a call with no name of its own.
  • An arrow function is a short form of a closure with one expression.

In this example, array_map adds a fifth of each price as tax. array_filter keeps the taxed prices of 24 or more with their keys. array_reduce then adds the kept prices into one total.

Note

The three functions read the input array and build fresh results, so the input array stays as it was.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does array_map return?