PHP 8.5 introduces a long-awaited feature: the pipe operator (|>). Inspired by functional programming, this operator makes code cleaner and easier to read by letting you pass values directly through a series of function calls or operations.
If you’ve ever written deeply nested function calls in PHP, you know how messy and hard to follow they can get. The pipe operator solves this problem elegantly.
The Problem Without Pipes
Traditionally, you might write code like this:
$result = strtoupper(trim(htmlspecialchars($input)));
While it works, the nesting can be confusing, especially when functions stack up.
Enter the Pipe Operator
With the pipe operator in PHP 8.5, the same logic becomes:
$result = $input
|> htmlspecialchars($$)
|> trim($$)
|> strtoupper($$);
Here’s how it works:
|>takes the value on its left and passes it into the expression on the right.- The placeholder
$$represents the piped value.
This makes the code read more like a sequence of transformations.
Another Example: Collections
Imagine filtering and transforming an array:
Old Way
$numbers = [1, 2, 3, 4, 5];
$result = array_map(
fn($n) => $n * 2,
array_filter($numbers, fn($n) => $n % 2 === 0)
);
New Way with Pipes
$numbers = [1, 2, 3, 4, 5];
$result = $numbers
|> array_filter($$, fn($n) => $n % 2 === 0)
|> array_map(fn($n) => $n * 2, $$);
Much clearer and more maintainable.
Benefits
- Readability: Code reads top to bottom, like a recipe.
- Maintainability: Easy to add or remove steps.
- Consistency: Works well with existing PHP functions and user-defined functions.
When to Use It
The pipe operator shines when you:
- Transform data step by step.
- Want to avoid deeply nested calls.
- Work with collections, strings, or streams of transformations.
Final Thoughts
The pipe operator (|>) in PHP 8.5 is a small addition with a big impact. It helps developers write cleaner, more expressive code that’s easier to maintain.
If you’re using Laravel, Symfony, or any modern PHP framework, you’ll find countless opportunities to simplify your code with pipes.