Chuyển đến nội dung

Bài 44 · Arrays

array_map, array_filter and array_reduce

Transform, filter and summarize PHP arrays with callbacks - array_map, array_filter, array_reduce, array_walk, PHP 8.4 array_find/any/all, 8.5 array_first and the pipe.

Many loops you write over arrays do one of three jobs: transform every element (prices to prices with tax), filter some elements out (only active users), or reduce the whole array to one value (a total, a maximum, a lookup table). PHP has a function for each job, and each takes a callback, a small function that says what to do with one element.

Writing array_filter($orders, fn($o) => $o['paid']) instead of a five-line loop makes the intent visible at a glance: "the paid orders". This lesson covers array_map(), array_filter() and array_reduce() in depth (including how each treats keys, the part that trips people up), array_walk(), the search helpers added in PHP 8.4 (array_find(), array_find_key(), array_any(), array_all()), array_first()/array_last() from PHP 8.5, and chaining all of them with the PHP 8.5 pipe operator |>.

The callbacks here are mostly arrow functions, fn($x) => $x * 2. If they're new to you, read Anonymous Functions and Closures first; the short version is that fn creates a one-expression function that can use variables from the surrounding code automatically.

array_map: transform every element

array_map($callback, $array) calls the callback once per element and returns a new array of the results. The original is untouched.

PHP Transforming with array_map

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

A callback can be any callable: an arrow function, a closure, a function name as a string ('strtoupper'), or the first-class callable syntax ucfirst(...) from PHP 8.1. The (...) form is checked when the line runs, works with methods too ($formatter->format(...)), and editors understand it, so prefer it over strings.

Keys and multiple arrays

With one array, array_map() keeps the keys, including string keys. With several arrays, it walks them in parallel, passes one element from each to the callback, and returns a plain list. If the arrays have different lengths, the shorter ones are padded with null.

PHP array_map keys and parallel arrays

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The ?int type on $c is needed because the third call gets null for the missing price. The last example shows the standard trick for using keys in array_map(): pass array_keys($array) alongside the array. As Multidimensional Arrays showed, array_map(null, $a, $b) with a null callback zips arrays into pairs.

array_filter: keep only some elements

array_filter($array, $callback) keeps the elements for which the callback returns a truthy value. Without a callback, it removes every falsy element.

PHP Filtering with and without a callback

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Two behaviors cause most array_filter() bugs:

  1. Keys are preserved. Filtering [0 => a, 1 => b, 2 => c] down to a and c leaves keys 0 and 2. A for loop with an index breaks, and json_encode() produces an object instead of a list. Wrap the result in array_values() when you need a clean list.
  2. Without a callback, '0' is removed, because the string '0' is falsy in PHP (see Booleans and null). That's rarely what you want for form input, where 0 can be a valid answer. Pass an explicit callback such as fn($v) => $v !== '', or fn($v) => $v !== null.

Filtering by key, or by key and value

By default the callback receives only the value. The third argument changes that: ARRAY_FILTER_USE_KEY passes only the key, and ARRAY_FILTER_USE_BOTH passes the value and then the key.

PHP ARRAY_FILTER_USE_KEY and ARRAY_FILTER_USE_BOTH

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

array_reduce: boil an array down to one value

array_reduce($array, $callback, $initial) carries an accumulator through the array. The callback receives the accumulator so far and the current element, and returns the new accumulator. The final accumulator is the result.

PHP
array_reduce([5, 10, 20], fn(int $carry, int $n): int => $carry + $n, 0);
// carry: 0 -> 5 -> 15 -> 35, so the result is 35
PHP Totals, maximums and lookup tables with array_reduce

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Always pass an initial value. Without one, the accumulator starts as null: the second example handles that on purpose with ?array, but a sum without 0 would start from null, and on an empty array you get null back instead of 0, as the last line shows.

array_reduce() is powerful but not always the clearest choice. For sums, array_sum(array_column($rows, 'total')) reads better; for building maps, array_column($rows, 'qty', 'item') does it in one call; and for anything with several steps, a plain foreach is often easiest to follow. Use the tool that makes the intent obvious.

array_walk: modify in place, with keys

array_walk(&$array, $callback, $extra) calls the callback with each value and its key, plus an optional extra argument. It returns true, not a new array; to change elements, declare the value parameter by reference (&$value):

PHP array_walk with references and keys

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

If the callback declares a third parameter, you must pass the extra argument to array_walk(); otherwise the call fails with an ArgumentCountError.

In modern code, array_map() (which returns a new array) is usually preferred over array_walk() with references. array_walk() shines when you need the key and the value, want to update a large array in place, or just want a callback-style loop for side effects. array_walk_recursive() does the same through nested arrays.

Finding elements: array_find, array_any and array_all (PHP 8.4)

PHP 8.4 added four functions that replace common "loop until found" code. Each takes a callback that receives the value and the key, and each stops at the first answer, so they don't scan the rest of the array:

Function Returns
array_find($array, $callback) The first value for which the callback is true, or null
array_find_key($array, $callback) The key of that value, or null
array_any($array, $callback) true if the callback is true for at least one element
array_all($array, $callback) true if the callback is true for every element
PHP array_find, array_find_key, array_any and array_all

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice the empty-array results: array_any([]) is false (no element passed) and array_all([]) is true (no element failed). That's standard logic, but worth remembering when an empty list should mean "not valid".

Because array_find() returns null both when nothing matches and when the matching element is null, use array_find_key() and compare with null when your array can contain null values.

array_first and array_last (PHP 8.5)

Getting the first or last value of an array used to need reset()/end() (which move the array's internal pointer and need a variable) or $a[array_key_first($a)]. PHP 8.5 adds array_first() and array_last(), which return the value directly, or null for an empty array. They work with any keys:

PHP array_first and array_last

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Chaining with the pipe operator |> (PHP 8.5)

Real tasks combine these steps: filter, then map, then reduce. Nesting the calls reads inside-out, and the arguments of array_map() and array_filter() are in opposite orders, which makes nested code hard to scan:

PHP
$result = array_sum(array_map(fn($o) => $o['total'], array_filter($orders, fn($o) => $o['paid'])));

PHP 8.5's pipe operator passes the value on its left as the single argument of the callable on its right: $x |> f(...) means f($x). A chain of pipes reads top to bottom, in the order things happen:

PHP A data pipeline with the pipe operator

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The rules of the pipe:

  • The right side must be a callable that takes one required argument. Functions like trim(...) and array_sum(...) fit directly. For functions that need more arguments, like array_filter(), wrap the call in an arrow function.
  • Arrow functions on the right of |> must be in parentheses. Without them, PHP stops with Fatal error: Arrow functions on the right hand side of |> must be parenthesized.
  • The pipe binds more loosely than arithmetic, so 1 + 2 |> f(...) means f(1 + 2).

The pipe needs PHP 8.5. On older versions, use intermediate variables, which are also perfectly readable: $paid = array_filter(...); $totals = array_column($paid, 'total'); $sum = array_sum($totals);.

Choosing between callbacks and foreach

These functions don't replace foreach; they complement it. Rules of thumb:

  • One clear step (transform, filter, check, find): use the function. It names the intent.
  • Several steps: a pipe or a few well-named intermediate variables.
  • Complex logic, early breaks, several outputs at once, or performance-critical loops over huge arrays: a foreach is often clearer and avoids creating intermediate arrays.
  • For very large or endless data, look at generators (Generators), which process one element at a time instead of building whole arrays.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. What does array_filter([10, 0, 20, 0]) return?

    Without a callback, falsy values (the zeros) are removed, and array_filter always preserves the original keys. Use array_values() to re-index.
  2. 2. What does array_map(fn($v) => $v * 2, ['a' => 1, 'b' => 2]) return?

    With a single array, array_map keeps the keys, including string keys.
  3. 3. What does array_reduce([], fn($c, $n) => $c + $n) return?

    Without an initial value, the accumulator starts as null, and for an empty array that null is returned. Pass 0 as the third argument for sums.
  4. 4. What does array_all([], fn($v) => $v > 0) return?

    No element fails the test, so "all elements pass" is true for an empty array. array_any([]) is false.
  5. 5. Which pipe expression is valid PHP 8.5?

    The right side must be a callable. trim(...) is a first-class callable; an arrow function must be wrapped in parentheses, and a bare name is a constant, not a callable.

Summary

  • array_map() transforms each element into a new array; with one array it keeps keys, with several it walks them in parallel and returns a list.
  • array_filter() keeps elements whose callback is truthy, preserves keys, and without a callback removes falsy values, including '0'. Use ARRAY_FILTER_USE_KEY or ARRAY_FILTER_USE_BOTH to see keys.
  • array_reduce() folds an array into one value; always pass an initial value.
  • array_walk() visits values and keys, modifying in place through a &$value parameter; it returns true.
  • PHP 8.4: array_find(), array_find_key(), array_any() and array_all() stop at the first answer.
  • PHP 8.5: array_first() and array_last() return the first/last value or null.
  • PHP 8.5's pipe |> chains one-argument callables top to bottom; wrap arrow functions in parentheses.
  • Use the function that states the intent; fall back to foreach for complex logic.

Next: Destructuring and Spread, where you'll unpack arrays into variables and combine them with ....

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.