Lesson 6 of 8 · 10 min

array_map, array_filter and usort

Instead of writing loops, you can hand a small function to PHP's array functions:

$numbers = [1, 2, 3, 4];

array_map(fn($n) => $n * 10, $numbers);          // [10, 20, 30, 40]
array_filter($numbers, fn($n) => $n % 2 === 0);  // [1 => 2, 3 => 4]
array_reduce($numbers, fn($sum, $n) => $sum + $n, 0);   // 10
array_sum($numbers);                              // 10

Note the argument order: array_map takes the function first, array_filter takes the array first. Everyone looks this up.

array_filter keeps the original keys, which leaves gaps. Wrap it in array_values(...) for a clean 0, 1, 2... list.

Sorting with your own rule

usort sorts with a comparison function returning a negative number, 0 or a positive number. The spaceship operator <=> does exactly that:

usort($people, fn($a, $b) => $a["age"] <=> $b["age"]);   // youngest first
usort($people, fn($a, $b) => $b["age"] <=> $a["age"]);   // oldest first

array_column($rows, "name") pulls one field out of every row.

Your task

Products are arrays like ["name" => "Pen", "price" => 1.2, "stock" => 10].

  1. withVat($prices): every price plus 15%, rounded to 2 decimals, with array_map.
  2. inStock($products): products with stock above 0, re-indexed, with array_filter.
  3. byPrice($products): sorted cheapest first, with usort.
  4. stockValue($products): the total of price times stock, with array_reduce.
index.php
<?php
function withVat($prices) {
}

function inStock($products) {
}

function byPrice($products) {
}

function stockValue($products) {
}

PHP 8.4 runs right here in your browser. The first run downloads about 12 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…