Array Functions: map, filter & reduce

Array Functions: map, filter & reduce in PHP: --- Walk into a busy restaurant kitchen at six in the morning and you find the prep cooks working a line.


The Analogy: A Restaurant Prep Line at Dawn

Walk into a busy restaurant kitchen at six in the morning and you find the prep cooks working a line. Crates of raw vegetables come in one end, and each cook along the bench has exactly one job. The first cook takes every single carrot from the crate and does the same thing to each: peel it, top and tail it, dice it to the same size. Nothing is judged or discarded here -- every carrot that goes in comes out as diced carrot. One in, one out, the same treatment applied uniformly down the whole crate.

That first station is what array_map does. It takes a collection and applies one identical transformation to every element, handing back a new collection of exactly the same size. The cook does not decide which carrots deserve dicing and which do not; that is not their job. Their job is the transformation, applied without exception, and the result is a fresh tray of transformed items while the original crate is left untouched on the floor behind them.

The second cook is a grader. They inspect each diced portion and make a single yes-or-no decision: is this good enough to keep? Bruised, discoloured, or undersized pieces are swept into a waste bin; the rest pass through unchanged. This cook never alters a portion -- they only keep or drop it. That is array_filter: same items, none of them changed, but only those that satisfy a test survive to the next station. The tray coming out is usually smaller than the tray going in.

The third cook tips everything that survived into one enormous stockpot and simmers it down over hours into a single, concentrated reduction. Dozens of ingredients go in; one pot of stock comes out. That is array_reduce: many values folded, one step at a time, into a single result. The line only works because each station stays pure. The moment the peeling cook also starts quietly binning carrots they dislike, or the grader starts seasoning as they sort, the head chef can no longer trust what any station produced -- and code that mixes transforming, selecting, and combining into one tangled callback becomes exactly as impossible to reason about.


Syntax or Core Structure

The three core functions each take an array and a callback. array_map transforms, array_filter selects, array_reduce folds. A subtle but important detail sits in how each treats array keys.

<?php
declare(strict_types=1);

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

// map: transform every element (keys are preserved 0..3).
$doubled = array_map(fn (int $n): int => $n * 2, $nums);
echo 'doubled: ' . implode(', ', $doubled), "\n";

// filter: keep matching elements -- and KEEP their original keys.
$evens = array_filter($nums, fn (int $n): bool => $n % 2 === 0);
echo 'evens (values): ' . implode(', ', $evens), "\n";
$pairs = [];
foreach ($evens as $k => $v) { $pairs[] = "{$k}=>{$v}"; }
echo 'evens (keys kept): ' . implode(', ', $pairs), "\n";

// reduce: fold to a single value, starting from 0.
$sum = array_reduce($nums, fn (int $carry, int $n): int => $carry + $n, 0);
echo 'sum: ' . $sum, "\n";

Output:

doubled: 2, 4, 6, 8
evens (values): 2, 4
evens (keys kept): 1=>2, 3=>4
sum: 10

The line that trips people up is the filtered keys. array_filter dropped the values 1 and 3, but it kept the surviving values at their original positions 1 and 3, giving the array [1 => 2, 3 => 4]. implode ignores keys so the values print cleanly, but if you later assume the result is numbered from zero -- say by reading index 0 -- you will be surprised. When you need a clean zero-based list after filtering, wrap the result in array_values.


Technical Depth: Choosing the Right Tool and Watching the Keys

What each function returns

These functions look similar but differ in argument order, return shape, and key handling. The table below is worth memorising.

FunctionCallback shapeReturnsKeys
array_mapfn($value)New array, same lengthPreserved (single-array form)
array_filterfn($value) returns boolSubset, same or smallerPreserved (gaps left behind)
array_reducefn($carry, $value)One accumulated valueNot applicable
usortfn($a, $b) returns intSorts in place, returns boolReindexed from zero

Two traps live in this table. First, array_map and array_filter take their array and callback in opposite orders -- array_map takes the callback first, array_filter takes the array first. Second, usort does not return the sorted array; it sorts the array you pass in place and returns true. Writing $sorted = usort($rows, ...) leaves $sorted holding true and silently discards nothing, which is a classic source of confusion.

Extracting and ordering rows

Real data usually arrives as a list of associative arrays -- rows from a database. Two functions turn that into something useful: array_column pulls one field out of every row, and usort orders the rows by a comparison.

<?php
declare(strict_types=1);

$products = [
    ['name' => 'Keyboard', 'price' => 4500],
    ['name' => 'Mouse',    'price' => 2500],
    ['name' => 'Monitor',  'price' => 30000],
];

// Pull just the names out of every row.
$names = array_column($products, 'name');
echo 'names: ' . implode(', ', $names), "\n";

// Order the rows by price, ascending. usort mutates $products in place.
usort($products, fn (array $a, array $b): int => $a['price'] <=> $b['price']);
echo "by price asc:\n";
foreach ($products as $p) {
    echo '  ' . $p['name'] . ' ' . number_format($p['price'] / 100, 2), "\n";
}

Output:

names: Keyboard, Mouse, Monitor
by price asc:
  Mouse 25.00
  Keyboard 45.00
  Monitor 300.00

The comparison uses the spaceship operator <=>, which returns a negative number, zero, or a positive number depending on order -- exactly what usort wants. array_column is the direct route from a list of rows to a list of one field, far clearer than a hand-written loop that pushes $row['name'] onto an accumulator. Note that usort reindexed the rows from zero after sorting, so unlike array_filter there are no gaps in the keys afterwards.

Reduce is not only for numbers

The carry of array_reduce can be any type, including an array. That makes reduce the natural tool for grouping -- folding a flat list of rows into a map keyed by some field. Here it totals sales by region.

<?php
declare(strict_types=1);

$sales = [
    ['region' => 'North', 'amt' => 10],
    ['region' => 'South', 'amt' => 5],
    ['region' => 'North', 'amt' => 3],
];

$byRegion = array_reduce($sales, function (array $carry, array $s): array {
    $carry[$s['region']] = ($carry[$s['region']] ?? 0) + $s['amt'];
    return $carry;
}, []);

foreach ($byRegion as $region => $total) {
    echo "{$region}: {$total}\n";
}

Output:

North: 13
South: 5

The carry starts as an empty array and grows one region at a time. North totals 10 + 3 = 13 and South totals 5. The output order is not random: PHP arrays remember insertion order, and North was seen first, so it prints first. The null coalescing operator ?? is doing quiet but essential work here: the first time a region is seen its key does not yet exist in the carry, so $carry[$s['region']] ?? 0 supplies the starting 0 instead of raising an undefined-key warning. Drop the ?? and the very first row of each group emits a warning and folds null into the sum. This is a genuinely useful pattern -- one pass turns a flat list into a grouped summary -- and it shows that array_reduce is far more general than the numeric sum most tutorials stop at.


Real World Example: An Order Summary Pipeline

A shopping cart needs a summary that ignores out-of-stock lines, works out each remaining line's total, and adds them into a grand total. That is the prep line exactly: filter selects the in-stock lines, map turns each line into its total, reduce folds those into one number. Chaining the three reads as a clean pipeline, each step doing one job.

<?php
declare(strict_types=1);

$items = [
    ['name' => 'Widget', 'qty' => 3, 'price' => 1200, 'inStock' => true],
    ['name' => 'Gadget', 'qty' => 2, 'price' => 4500, 'inStock' => false],
    ['name' => 'Gizmo',  'qty' => 5, 'price' => 800,  'inStock' => true],
];

// filter: drop anything out of stock.
$available = array_filter($items, fn (array $i): bool => $i['inStock']);

// map: turn each surviving line into [name, lineTotalCents].
$lines = array_map(
    fn (array $i): array => [$i['name'], $i['qty'] * $i['price']],
    $available
);

// reduce: fold the line totals into a grand total.
$grand = array_reduce($lines, fn (int $carry, array $ln): int => $carry + $ln[1], 0);

echo "ORDER SUMMARY\n";
echo str_repeat('-', 13), "\n";
foreach ($lines as $ln) {
    printf("%-10s %8s\n", $ln[0], '$' . number_format($ln[1] / 100, 2));
}
echo str_repeat('-', 13), "\n";
printf("%-10s %8s\n", 'Total', '$' . number_format($grand / 100, 2));

Output:

ORDER SUMMARY
-------------
Widget       $36.00
Gizmo        $40.00
-------------
Total        $76.00

The pipeline drops Gadget because it is out of stock, then computes Widget as three at 1200 cents ($36.00) and Gizmo as five at 800 cents ($40.00), folding to a grand total of 7600 cents, printed as $76.00. Each function does one thing, and the data flows in one direction, so a reader can check each stage independently. Compared with a single foreach that filters, multiplies, and accumulates all at once, the pipeline is far easier to test: you can assert on $available, on $lines, and on $grand separately.

The pipeline is clean, but it hides a real efficiency flaw that matters at scale. Each of array_filter, array_map, and array_reduce walks the collection and builds a brand-new intermediate array, so a cart of ten thousand lines is traversed three times and allocates two full throwaway arrays before producing one number. For a shopping cart that is irrelevant, but the same style applied to a million-row dataset would use far more memory than a single loop or a generator that streams one row at a time. The pipeline also silently assumes every price and qty key is present and integer; a malformed row missing price would raise a warning and poison the total with null, because none of the three stages validates its input. A production version would validate each row before the arithmetic and, for very large inputs, prefer a lazy generator over eager intermediate arrays.


Common Mistakes

  1. Swapping the argument order of array_map and array_filter. array_map takes the callback first, then the array; array_filter takes the array first, then the callback. Getting them backwards is a TypeError, or worse, silently wrong behaviour.
  1. Assuming array_filter reindexes. It preserves the original keys, leaving gaps. If you then read index 0 of the result and it was filtered out, you get null or an undefined-key warning. Wrap in array_values when you need a clean list.
  1. Expecting usort to return the sorted array. It sorts in place and returns true. Writing $sorted = usort($rows, ...) throws away the sort result and leaves $sorted holding a boolean.
  1. Putting side effects in a map or filter callback. A callback that echoes, writes to a database, or mutates an outer variable turns a pure transformation into something with hidden consequences, and the order of evaluation is not something you should rely on.
  1. Forgetting the initial value of array_reduce. With no third argument the initial carry is null, so the first $carry + $n may behave unexpectedly under strict types or with string concatenation. Always pass a sensible starting value.
  1. Reaching for array_reduce when a built-in exists. Summing with array_reduce is slower and less clear than array_sum; the same goes for array_product, min, max, and count. Use the purpose-built function when there is one.
  1. Chaining many passes over a huge array. Each of map, filter, and reduce builds a new array and walks the whole collection. On large data this multiplies memory and time; a single loop or a generator is far leaner.
  1. Mutating the array being iterated inside a callback. Changing the source array while array_map or array_filter is running leads to undefined behaviour. Treat the input as read-only and return new data.
  1. Assuming array_map with multiple arrays preserves string keys. When you pass more than one array, array_map reindexes the result numerically and ignores the keys, unlike the single-array form. This surprises people who relied on keys being kept.

Best Practices

  • Keep each callback pure: it should compute a return value from its arguments and nothing else. No echoing, no writing to outer state.
  • Use the most specific built-in available -- array_sum, array_product, array_column, in_array -- before reaching for a general array_reduce or a hand-written loop.
  • Call array_values after array_filter whenever downstream code expects a zero-based list rather than the original sparse keys.
  • Prefer arrow functions for these callbacks. Their single-expression bodies keep the transformation visible and discourage hidden side effects.
  • Type-hint callback parameters and return types; a wrong element type then fails loudly at the callback rather than deep inside later code.
  • For very large collections, prefer a generator or a single foreach over chaining multiple array passes, to avoid building throwaway intermediate arrays.
  • Use the spaceship operator <=> in usort comparisons rather than subtracting values, which can overflow or mis-order floats.
  • Name intermediate results ($available, $lines, $grand) so each stage of a pipeline is independently readable and testable.

Practice Exercises

  1. Given an array of temperatures in Celsius, use array_map to convert each to Fahrenheit, then array_filter to keep only those above 100 Fahrenheit, then array_values to reindex. Print the survivors.
  1. You have a list of order rows, each an associative array with total in cents and a status. Use array_filter to keep only paid orders and array_reduce to sum their totals, then print the revenue as dollars.
  1. Use array_column to build a lookup that maps each user's id to their email from a list of user rows, by passing both the value key and the index key to array_column. Print the resulting map.
  1. Given a list of products with name and price, sort them by price descending with usort, then take the three most expensive with array_slice. Explain in a comment why usort returns true rather than the sorted array.