Learn/PHP/14. Array functions and the pipe operator
Lesson 14 of 15
Sign in

PHP, lesson 14

Array functions and the pipe operator

The associative array is PHP's signature data structure, and the standard library has more than seventy functions for working with it. Learning a handful of them changes how you write PHP: instead of a loop that builds a result step by step, you describe the transformation and let the function do the looping.

Callbacks and arrow functions

Most array functions take a callback, a function they call for each element. The short way to write one is an arrow function: fn(parameters) => expression. It returns the expression's value and can read variables from the surrounding code automatically.

You can also pass an existing function with the first-class callable syntax: strtoupper(...) creates a callable from strtoupper.

The big three: map, filter, reduce

Watch the argument order: array_map() takes the callback , while and take the array first.

2 exercises to try what you just read.

Exercise 1

Cart totals

Press Ctrl Enter or Check to test your code.

Exercise 2

Slug maker

Press Ctrl Enter or Check to test your code.

first
array_filter()
array_reduce()

Because array_filter() keeps the original keys, filtering a list can leave gaps such as [0 => 5, 2 => 9]. Call array_values() to renumber it. To filter by key, or by key and value, pass ARRAY_FILTER_USE_KEY or ARRAY_FILTER_USE_BOTH as the third argument.

Working with rows

Real data often arrives as a list of associative arrays, like rows from a database:

array_combine($keys, $values) builds a map from two lists, and the spread operator [...$a, ...$b] merges arrays inline.

Newer helpers

Recent versions added functions that replace common hand-written loops:

  • array_find($a, $callback) returns the first value that matches, or null (PHP 8.4).
  • array_any() and array_all() answer "does any / every element match?" (PHP 8.4).
  • array_first($a) and array_last($a) return the first or last value, or null for an empty array (PHP 8.5).

The pipe operator

PHP 8.5 introduced the pipe operator |>. It passes the value on its left into the callable on its right, so a series of transformations reads top to bottom instead of inside out:

Each step must be a callable that takes exactly one argument. Arrow functions need parentheses around them in a pipe, as shown above. When a function needs extra arguments, like str_replace(), wrap it in a small arrow function.

Choosing between loops and functions

A foreach loop is still perfectly good PHP, especially when one pass does several things at once. Reach for the array functions when each step is a single clear transformation; the result is usually shorter and easier to read.

Further reading

  • Arrow functions
  • array_map(), array_filter() and array_reduce()
  • array_column()
  • array_find()
  • Functional operators: the pipe operator
  • PHP 8.5 release notes

Each input line is a cart row: name price qty. The starter loads them into $cart as associative arrays. Using array functions (no foreach needed):

  1. Remove rows whose quantity is 0 (array_filter).
  2. Print items: N, the number of rows left.
  3. Print total: X.XX, the sum of price × quantity.
  4. Print biggest: NAME, the row with the largest line total (array_reduce; on a tie keep the earlier row). If the cart is empty, print biggest: none.

Sample input:

Sample output:

Websites turn titles into URL "slugs". For each input line, build the slug with a chain of pipe operators:

  1. trim surrounding spaces,
  2. lowercase it,
  3. replace every run of characters that are not a–z or 0–9 with a single - (preg_replace('/[^a-z0-9]+/', '-', $s)),
  4. trim - from both ends.

Print each slug on its own line. If a slug ends up empty, print untitled instead.

Sample input:

Sample output:

<?php

$rate = 1.2;
$withTax = fn(float $price): float => $price * $rate;
echo $withTax(10), "\n";   // 12
<?php

$prices = ["tea" => 2.5, "cake" => 3.0, "water" => 0.0];

// array_map: transform every value (keys are kept for a single array)
$doubled = array_map(fn($p) => $p * 2, $prices);

// array_filter: keep the values where the callback returns true (keys are kept)
$paid = array_filter($prices, fn($p) => $p > 0);

// array_reduce: fold everything into one value, starting from the initial value
$total = array_reduce($prices, fn($carry, $p) => $carry + $p, 0.0);
<?php

$cart = [
    ["name" => "tea", "price" => 2.5, "qty" => 2],
    ["name" => "cake", "price" => 3.0, "qty" => 1],
];

$names = array_column($cart, "name");              // ["tea", "cake"]
$byName = array_column($cart, "price", "name");    // ["tea" => 2.5, "cake" => 3.0]
$lineTotals = array_map(fn($row) => $row["price"] * $row["qty"], $cart);
echo array_sum($lineTotals), "\n";                 // 8
<?php

$title = "  Hello PHP  ";

// without the pipe: read from the innermost call outwards
$shout = strtoupper(str_replace(" ", "_", trim($title)));

// with the pipe: read in the order things happen
$shout = $title
    |> trim(...)
    |> (fn($s) => str_replace(" ", "_", $s))
    |> strtoupper(...);
tea 2.50 2
cake 3.00 1
gum 0.99 0
milk 1.20 3
items: 3
total: 11.60
biggest: tea
  Hello, World!
PHP 8.5 Released
hello-world
php-8-5-released