The pipe operator |>

suggest change

PHP 8.5 added the pipe operator |>. It takes the value on its left and passes it as the only argument to the callable on its right:

$result = $value |> someFunction(...);
// same as
$result = someFunction($value);

You can chain pipes, so a series of transformations reads from left to right (or top to bottom) in the order they happen. Nested calls read from the inside out.

This article covers how the operator works, what can go on its right side, why arrow functions need parentheses, how precedence works, the restrictions (one argument, no references), and practical pipelines for strings and arrays. All examples were run with PHP 8.5. In error messages, paths are shortened to /app/.

The right side is usually a callable created with the first-class callable syntax strlen(...), which PHP 8.1 added. See Callable for the different kinds of callables and Closures for anonymous functions.

Nested calls, temporary variables and pipes

Here's the same slug function written three ways:

<?php
$title = '  Hello, PHP 8.5 World!  ';

// nested calls: read from the inside out
$slug1 = strtolower(trim(preg_replace('/[^a-z0-9]+/i', '-', trim($title)), '-'));

// temporary variables
$s = trim($title);
$s = preg_replace('/[^a-z0-9]+/i', '-', $s);
$s = trim($s, '-');
$slug2 = strtolower($s);

// pipe operator: read from left to right
$slug3 = $title
    |> trim(...)
    |> (fn($s) => preg_replace('/[^a-z0-9]+/i', '-', $s))
    |> (fn($s) => trim($s, '-'))
    |> strtolower(...);

echo $slug1, "\n", $slug2, "\n", $slug3, "\n";

Output:

hello-php-8-5-world
hello-php-8-5-world
hello-php-8-5-world

The nested version is hard to read: the first operation (trim($title)) is in the middle, and the argument '-' ends up far away from the trim it belongs to. The temporary variable version is readable, but it reassigns $s over and over. The pipe version lists the steps in order and needs no variable.

How it works

$a |> $f evaluates $a, then evaluates $f (which must give a callable), then calls it with $a as the single argument. The result of the call is the value of the whole expression.

The operator is left-associative, so $a |> $f |> $g means ($a |> $f) |> $g. A chain is the same as a series of assignments to a temporary variable:

<?php
$result = '  hello  ' |> trim(...) |> strtoupper(...) |> strrev(...);

// is the same as:
$tmp = '  hello  ';
$tmp = trim($tmp);
$tmp = strtoupper($tmp);
$tmp = strrev($tmp);

var_dump($result, $tmp);

Output:

string(5) "OLLEH"
string(5) "OLLEH"

The steps run strictly in order. The left side is evaluated first, then the callable expression on the right, then the call, and only then the next step:

<?php
function step(string $name): Closure
{
    echo "creating $name\n";
    return function (int $n) use ($name): int {
        echo "calling $name($n)\n";
        return $n + 1;
    };
}

function start(): int
{
    echo "start\n";
    return 0;
}

$r = start() |> step('a') |> step('b');
var_dump($r);

Output:

start
creating a
calling a(0)
creating b
calling b(1)
int(2)

The pipe is not lazy and does not short-circuit. If a step throws an exception, the remaining steps don't run.

What can go on the right side

Any expression that evaluates to a callable works:

<?php
class Text
{
    public static function shout(string $s): string { return strtoupper($s) . '!'; }
    public function wrap(string $s): string { return "[$s]"; }
    public function __invoke(string $s): string { return "<$s>"; }
}

$text = new Text();
$exclaim = fn(string $s): string => "$s?!";

echo 'a' |> strtoupper(...), "\n";      // first-class callable
echo 'b' |> 'strtoupper', "\n";         // string callable
echo 'c' |> Text::shout(...), "\n";     // static method
echo 'd' |> 'Text::shout', "\n";        // static method as string
echo 'e' |> $text->wrap(...), "\n";     // instance method
echo 'f' |> [$text, 'wrap'], "\n";      // array callable
echo 'g' |> $text, "\n";                // object with __invoke
echo 'h' |> $exclaim, "\n";             // closure in a variable
echo 'i' |> (fn($s) => "$s$s"), "\n";   // inline arrow function
echo 'j' |> (function (string $s): string {
    return str_repeat($s, 3);
}), "\n";                               // inline anonymous function

Output:

A
B
C!
D!
[e]
[f]
<g>
h?!
ii
jjj

Prefer the name(...) syntax over strings and arrays. With strtoupper(...) a typo in the function name is reported where you wrote it, IDEs can find usages and rename it, and PHP compiles $x |> strtoupper(...) into a plain strtoupper($x) call without creating a Closure object.

If the right side isn't callable, you get an Error at runtime: 'a' |> 'nope' throws "Call to undefined function nope()", and 'a' |> 42 throws "Value of type int is not callable".

Arrow functions need parentheses

Most functions need more than one argument. To pipe into them, wrap the call in an arrow function that receives the piped value and supplies the other arguments:

<?php
$csv = 'banana, apple ,cherry';

$list = $csv
    |> (fn($s) => explode(',', $s))
    |> (fn($parts) => array_map(trim(...), $parts))
    |> (fn($parts) => array_filter($parts, fn($p) => $p !== 'apple'))
    |> (fn($parts) => implode(' | ', $parts));

echo $list, "\n";

Output:

banana | cherry

The parentheses around each arrow function are required. An arrow function's body extends as far to the right as possible, so without parentheses the body of the first fn would include all the following pipe steps. PHP rejects that at compile time:

<?php
$total = 3 |> fn($x) => $x * 2 |> strval(...);

Output:

Fatal error: Arrow functions on the right hand side of |> must be parenthesized in /app/pipe.php on line 2

An arrow function inside a pipe step is a new closure created on every execution, which is a little slower than a direct call. This only matters in hot loops.

Precedence

|> binds looser than arithmetic, string concatenation and bit shifts, and tighter than comparison, ??, the ternary operator and assignment:

<?php
$double = fn(int $n): int => $n * 2;

// arithmetic and . bind tighter: the whole left side is piped
var_dump(1 + 2 |> $double);              // $double(1 + 2)
var_dump('ab' . 'c' |> strtoupper(...)); // strtoupper('ab' . 'c')

// comparison, ??, ?: and = bind looser: the pipe is done first
var_dump('abc' |> strlen(...) === 3);    // strlen('abc') === 3
var_dump(null ?? 'x' |> strtoupper(...)); // null ?? strtoupper('x')
$len = 'hello' |> strlen(...);           // $len = strlen('hello')
var_dump($len);

// to do arithmetic on the result, wrap the pipe in parentheses
var_dump(('abc' |> strlen(...)) + 1);
try {
    var_dump('abc' |> strlen(...) + 1);  // 'abc' |> (strlen(...) + 1)
} catch (TypeError $e) {
    echo $e->getMessage(), "\n";
}

Output:

int(6)
string(3) "ABC"
bool(true)
string(1) "X"
int(5)
int(4)
Unsupported operand types: Closure + int

The last case is the one to watch: + binds tighter than |>, so PHP tries to add 1 to the closure. When a pipe is part of a bigger expression, add parentheses even if they aren't strictly needed.

One argument, passed by value

The callable on the right is always called with exactly one argument, so:

<?php
$numbers = [3, 1, 2];

// a function with more than one required parameter
try {
    $numbers |> array_map(...);
} catch (ArgumentCountError $e) {
    echo get_class($e), ': ', $e->getMessage(), "\n";
}

// a function that takes its parameter by reference
try {
    $numbers |> sort(...);
} catch (Error $e) {
    echo get_class($e), ': ', $e->getMessage(), "\n";
}

// optional parameters are fine: they get their default values
function excerpt(string $s, int $max = 10): string
{
    return strlen($s) > $max ? substr($s, 0, $max) . '...' : $s;
}
echo 'The quick brown fox' |> excerpt(...), "\n";

// a void function returns null into the rest of the chain
function logValue(mixed $v): void
{
    echo 'log: ', json_encode($v), "\n";
}
var_dump($numbers |> logValue(...));

Output:

ArgumentCountError: array_map() expects at least 2 arguments, 1 given
Error: sort(): Argument #1 ($array) could not be passed by reference
The quick ...
log: [3,1,2]
NULL

For by-reference functions, write a wrapper that takes the value as a normal parameter, works on that copy and returns it, like the sortBy() helper below.

There's also no null-safe pipe. If a step can return null and the next step doesn't accept it, you get a TypeError (in strict mode) or a deprecation (in coercive mode for internal functions). Handle null in a step yourself:

<?php
declare(strict_types=1);

function findUserName(int $id): ?string
{
    return [1 => 'ann'][$id] ?? null;
}

try {
    echo 2 |> findUserName(...) |> strtoupper(...), "\n";
} catch (TypeError $e) {
    echo $e->getMessage(), "\n";
}

// handle null yourself: the pipe has no null-safe variant
$name = 2 |> findUserName(...) |> (fn(?string $n) => $n === null ? null : strtoupper($n));
var_dump($name);

Output:

strtoupper(): Argument #1 ($string) must be of type string, null given
NULL

Pipelines over arrays with helper functions

Wrapping every step in fn($items) => array_map(..., $items) is noisy. A common pattern is to write small helpers that take the extra arguments and return a one-parameter closure. The pipeline then reads like a list of operations:

<?php
declare(strict_types=1);

// Each helper takes the "extra" arguments and returns a one-parameter closure.
function map(callable $fn): Closure
{
    return fn(array $items): array => array_map($fn, $items);
}

function filter(callable $fn): Closure
{
    return fn(array $items): array => array_values(array_filter($items, $fn));
}

function sortBy(callable $key, bool $desc = false): Closure
{
    return function (array $items) use ($key, $desc): array {
        usort($items, fn($a, $b) => $desc ? $key($b) <=> $key($a) : $key($a) <=> $key($b));
        return $items;
    };
}

function take(int $n): Closure
{
    return fn(array $items): array => array_slice($items, 0, $n);
}

$orders = [
    ['customer' => 'ann', 'total' => 120.0, 'status' => 'paid'],
    ['customer' => 'bob', 'total' => 35.5, 'status' => 'paid'],
    ['customer' => 'cid', 'total' => 410.0, 'status' => 'cancelled'],
    ['customer' => 'dee', 'total' => 89.9, 'status' => 'paid'],
    ['customer' => 'eve', 'total' => 250.0, 'status' => 'paid'],
];

$top = $orders
    |> filter(fn($o) => $o['status'] === 'paid')
    |> sortBy(fn($o) => $o['total'], desc: true)
    |> take(3)
    |> map(fn($o) => sprintf('%-4s %8.2f', $o['customer'], $o['total']));

echo implode("\n", $top), "\n";

$revenue = $orders
    |> filter(fn($o) => $o['status'] === 'paid')
    |> map(fn($o) => $o['total'])
    |> array_sum(...);

echo "revenue: $revenue\n";

Output:

eve    250.00
ann    120.00
dee     89.90
revenue: 495.4

The helpers also fix the inconsistent argument order of the built-in functions (array_map takes the callback first, array_filter takes it second). See Common functional methods in PHP for the underlying functions. Pipelines are easiest to reason about when every step is a pure function that returns a new value instead of modifying its input.

sortBy() can call usort() on $items because the array was passed by value, so the closure sorts its own copy.

Lazy pipelines with generators

The steps don't have to work on arrays. If they take and return iterables, you can build a lazy pipeline with generators. Nothing is read until the result is iterated, and reading stops when enough items were produced:

<?php
function lines(string $text): Generator
{
    foreach (explode("\n", $text) as $i => $line) {
        echo "  read line $i\n";
        yield $line;
    }
}

function lazyFilter(callable $fn): Closure
{
    return function (iterable $items) use ($fn): Generator {
        foreach ($items as $k => $v) {
            if ($fn($v)) {
                yield $k => $v;
            }
        }
    };
}

function lazyTake(int $n): Closure
{
    return function (iterable $items) use ($n): Generator {
        if ($n <= 0) {
            return;
        }
        foreach ($items as $k => $v) {
            yield $k => $v;
            if (--$n === 0) {
                return;
            }
        }
    };
}

$log = "INFO start\nERROR disk full\nINFO retry\nERROR timeout\nERROR again\nINFO done";

$errors = $log
    |> lines(...)
    |> lazyFilter(fn($l) => str_starts_with($l, 'ERROR'))
    |> lazyTake(2);

echo "nothing read yet\n";
foreach ($errors as $i => $line) {
    echo "line $i: $line\n";
}

Output:

nothing read yet
  read line 0
  read line 1
line 1: ERROR disk full
  read line 2
  read line 3
line 3: ERROR timeout

Only 4 of the 6 lines were read. The pipe itself is still eager: it calls lines(), lazyFilter(...) and lazyTake(2) right away, but each of those just creates a generator.

Debugging a pipeline with tap

To see the value between two steps, insert a step that prints the value and returns it unchanged:

<?php
function tap(callable $fn): Closure
{
    return function (mixed $value) use ($fn): mixed {
        $fn($value);
        return $value;
    };
}

$dump = fn(string $label) => tap(fn($v) => print("$label: " . json_encode($v) . "\n"));

$words = ' the  pipe   operator '
    |> trim(...)
    |> $dump('trimmed')
    |> (fn($s) => preg_split('/\s+/', $s))
    |> $dump('split')
    |> (fn($w) => array_map(ucfirst(...), $w))
    |> (fn($w) => implode(' ', $w));

echo $words, "\n";

Output:

trimmed: "the  pipe   operator"
split: ["the","pipe","operator"]
The Pipe Operator

Each step is on its own line, so you can comment out a step or add a tap without touching the others.

Validating input

A pipeline is a good fit for normalizing and validating a value. A step that throws stops the chain:

<?php
declare(strict_types=1);

function requireEmail(string $s): string
{
    return filter_var($s, FILTER_VALIDATE_EMAIL) !== false
        ? $s
        : throw new InvalidArgumentException("invalid email: '$s'");
}

function normalizeEmail(string $raw): string
{
    return $raw
        |> trim(...)
        |> strtolower(...)
        |> requireEmail(...);
}

foreach (['  Ann@Example.COM ', 'bob at example.com'] as $input) {
    try {
        echo normalizeEmail($input), "\n";
    } catch (InvalidArgumentException $e) {
        echo $e->getMessage(), "\n";
    }
}

Output:

ann@example.com
invalid email: 'bob at example.com'

When to use the pipe operator

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents