Tech News
← Back to articles

PHP 8.5 adds pipe operator

read original related products more articles

PHP 8.5, due out November of this year, will bring with it another long-sought-after feature: the pipe operator ( |> ). It's a small feature with huge potential, yet it still took years to happen.

What is a pipe operator?

The pipe operator, spelled |> , is deceptively simple. It takes the value on its left side and passes it as the single argument to a function (or in PHP's case, callable ) on its right side:

$result = "Hello World" |> strlen(...) // Is equivalent to $result = strlen("Hello World");

On its own, that is not all that interesting. Where it becomes interesting is when it is repeated, or chained, to form a "pipeline." For example, here's real code from a real project I've worked on, recast to use pipes:

$arr = [ new Widget(tags: ['a', 'b', 'c']), new Widget(tags: ['c', 'd', 'e']), new Widget(tags: ['x', 'y', 'a']), ]; $result = $arr |> fn($x) => array_column($x, 'tags') // Gets an array of arrays |> fn($x) => array_merge(...$x) // Flatten into one big array |> array_unique(...) // Remove duplicates |> array_values(...) // Reindex the array. ; // $result is ['a', 'b', 'c', 'd', 'e', 'x', 'y']

The same code without pipes would require either this horribly ugly nest of evil:

array_values(array_unique(array_merge(...array_column($arr, 'tags'))));

Or manually creating a temporary variable for each step. While temp variables are not the worst thing in the world, they are extra mental overhead, and mean that a chain like that cannot be used in a single-expression context, like a match() block. A pipe chain can.

Anyone who has worked on the Unix/Linux command line will likely recognize the similarity to the shell pipe, | . That's very deliberate, as it is effectively the same thing: Use the output from the left side as the input on the right side.

... continue reading