Use Pipe Operator in PHP 8.5

Use Pipe Operator in PHP 8.5

Since PHP 8.5, we can use the pipe operator (|>) for chaining multiple callables from left to right, passing the return value of each callable as the input to the next. The pipe operator makes it easier to chain multiple callables in a readable way, avoiding deeply nested calls or the need for temporary variables to hold intermediate results.

Let's take a look in the following example:

<?php

$input = ' Hello World ';

$output = ucfirst(strtolower(trim($input))); // Hello world

While this works perfectly, the nested calls can become hard to read, especially as the number of transformations grows.

Since PHP 8.5, the same logic can be expressed more clearly using the pipe operator:

<?php

$input = ' Hello World ';

$output = $input |> trim(...) |> strtolower(...) |> ucfirst(...); // Hello world
// or
$output = $input
        |> trim(...)
        |> strtolower(...)
        |> ucfirst(...);

The code uses the pipe operator to pass the result of one callable to the next. The first-class callable syntax with (...) lets us use functions directly in the pipeline.

For example, transforming a string into a URL-friendly format can be done using nested calls as follows:

<?php

$input = 'Learn PHP: New Features!';

$output = strtolower(
    str_replace(
        ' ',
        '-',
        preg_replace('/[^a-zA-Z0-9 ]/', '', $input)
    )
); // learn-php-new-features

With the pipe operator, the example can be rewritten like this:

<?php

$input = 'Learn PHP: New Features!';

$output = $input
    |> (fn (string $val) => preg_replace('/[^a-zA-Z0-9 ]/', '', $val))
    |> (fn (string $val) => str_replace(' ', '-', $val))
    |> strtolower(...); // learn-php-new-features

The pipe operator isn't limited to built-in functions - any callable can be used in a pipeline. We can mix user-defined functions, built-in functions, class static methods, anonymous functions, and more.

Leave a Comment

Cancel reply

Your email address will not be published.