array_map, filter, reduce

Four functions of PHP cover most work on a list: one builds a new list, one keeps a part of it, one folds it into a single value and one turns rows into columns. Each block below runs on its own data and prints the result.

array_map

Function array_map builds a new array by applying a callback to every item. The input stays unchanged and the output has the same length.

Arrow functions keep the call short. Use them for pure transforms like trimming or uppercasing.

<?php $names = ["anna", "bob"]; $upper = array_map(fn($v) => strtoupper($v), $names); echo implode(", ", $upper), PHP_EOL; echo implode(", ", $names), PHP_EOL;

php map.php

ANNA, BOB
anna, bob

The second line still holds the original names, which proves the sentence above: the map produced a new array and left its input alone.

array_filter

Function array_filter keeps only items where the callback returns true. Without a callback it drops falsy values like zero and empty string.

Remember that keys survive filtering, so reindex with array_values when order without gaps matters.

<?php $nums = [1, 2, 3, 4]; $even = array_filter($nums, fn($v) => $v % 2 === 0); echo implode(", ", $even), PHP_EOL; echo implode(", ", array_keys($even)), PHP_EOL; echo implode(", ", array_values($even)), PHP_EOL;

php filter.php

2, 4
1, 3
2, 4

The values are the two even numbers, but they still sit at the keys 1 and 3 of the original list; array_values() renumbers them from zero.

array_reduce

Function array_reduce folds a list into a single value like a sum or a string. The carry holds the running result while each item updates it.

Always set the starting value explicitly so empty arrays return a sane default instead of null.

<?php $nums = [1, 2, 3]; $sum = array_reduce($nums, fn($c, $v) => $c + $v, 0); echo $sum, PHP_EOL; var_dump(array_reduce([], fn($c, $v) => $c + $v, 0));

php reduce.php

6
int(0)

The fold adds the three numbers to the starting zero, and the empty list returns that zero instead of null because the third argument is there.

array_column

Function array_column pulls one field out of a list of rows. It is ideal for turning query results into plain lists of names or ids.

Pass a second field name to index the result by id and get fast lookup without loops.

<?php $users = [ ["id" => 1, "name" => "Ann"], ["id" => 2, "name" => "Bob"], ]; echo implode(", ", array_column($users, "name")), PHP_EOL; $byId = array_column($users, "name", "id"); echo $byId[2], PHP_EOL;

php column.php

Ann, Bob
Bob

The first call returns the names as a plain list, the second one keys the same names by the id field, so $byId[2] finds Bob with no loop.

Exercises

  1. Map a list of prices to strings with two decimal places and print them.
  2. Filter a list of words down to the ones longer than three letters and reindex the result.
  3. Fold a list of lines into one string with a comma between them.
  4. Build a list of emails from a list of users and look one up by id.
  5. Drop falsy values from [0, 1, "", "a", null] without a callback and print what is left.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does array_map() return?

    Answer

    A new array with one result per input item

    The callback runs once per item and its results form the new array, which keeps the length of the input.

  2. Which values does array_filter() drop when it is called without a callback?

    Answer

    Falsy values such as 0, an empty string and null

    With no callback the item itself is tested, and a falsy item is removed.

  3. What happens to the keys of an array after array_filter()?

    Answer

    They are kept as they were

    Filtering removes items but not key positions, so array_values() is the call that renumbers.

  4. What does the third argument of array_column($rows, "name", "id") do?

    Answer

    It keys the result by the id field

    The third argument names the field whose value becomes the key of each result row.

  5. What does this program print? <?php $names = ["anna", "bob"]; $upper = array_map(fn($v) => strtoupper($v), $names); echo implode(", ", $upper);

    Answer

    ANNA, BOB

    The callback uppercases each item and implode joins the two results with a comma.

  6. What does this program print? <?php $nums = [1, 2, 3, 4]; $even = array_filter($nums, fn($v) => $v % 2 === 0); echo implode(", ", $even);

    Answer

    2, 4

    Only 2 and 4 return true from the callback, and implode prints their values.

  7. What does this program print? <?php $nums = [1, 2, 3, 4]; $even = array_filter($nums, fn($v) => $v % 2 === 0); echo implode(", ", array_keys($even));

    Answer

    1, 3

    The even values sat at index 1 and 3, and filtering keeps those keys.

  8. What does this program print? <?php $nums = [1, 2, 3]; echo array_reduce($nums, fn($c, $v) => $c + $v, 0);

    Answer

    6

    The carry starts at 0 and each item is added to it: 1, then 3, then 6.

  9. What does this program print? <?php $users = [["id" => 1, "name" => "Ann"], ["id" => 2, "name" => "Bob"]]; $byId = array_column($users, "name", "id"); echo $byId[2];

    Answer

    Bob

    The third argument makes the id the key, so the row with id 2 answers for $byId[2].

  10. What does this program print? <?php var_dump(array_reduce([], fn($c, $v) => $c + $v));

    Answer

    NULL

    Without a starting value an empty list has nothing to return, so the result is null.

The code on this page was run with PHP 8.5.13 (php -v) in Alpine Linux, with the commands shown above.

Article author: Arthur Isaev