Data processing is one of those tasks that starts simple and becomes increasingly complex as an application grows. Importing a CSV file, processing API responses, or transforming data before saving it to a database often requires several operations executed in a specific order.
PHP 8.5 introduces the pipe operator (|>), a new language feature that makes these transformations easier to read, organize, and maintain. Rather than nesting function calls or creating temporary variables for every operation, developers can express a sequence of transformations from left to right.
In this article, we’ll explore how the pipe operator works and build a lightweight CSV import pipeline using PHP 8.5, backed enums, readonly classes, and native PHP functions. The objective is not simply to demonstrate new syntax, but to see how it can improve the structure of a real application.
Understanding PHP 8.5’s Pipe Operator
Before PHP 8.5, transforming a value through several functions typically required nested calls or intermediate variables. Consider a simple example that prepares a title for further processing.
<?php
$title = " Modern PHP Development ";
$result = strtolower(trim($title));
echo $result;
// modern php developmentThis example is straightforward, but as more transformations are introduced, nested expressions can become difficult to follow. With PHP 8.5, we can rewrite the same operation using the pipe operator:
<?php
$title = " Modern PHP Development ";
$result = $title
|> trim(...)
|> strtolower(...);
echo $result;
// modern php developmentThe value on the left is passed to the callable on the right. The returned value becomes the input for the next operation.
Notice the trim(...) and strtolower(...) syntax. These are first-class callables, introduced in PHP 8.1, which allow existing functions to be referenced as callable objects.
The pipe operator accepts a callable that can process one argument. Functions requiring additional parameters need to be wrapped in a closure that supplies those parameters.
Now let’s move beyond a basic string transformation and build something more useful.
A Real-World Example: Building a CSV Import Pipeline
Imagine an application that needs to import newsletter subscribers from a CSV file. Each record contains an email address, a subscriber name, and a subscription plan.
A typical import process involves reading the file, cleaning the input, validating the fields, converting the values into application objects, and finally storing or exporting the results.
Instead of implementing everything in a single function, we’ll divide the process into three independent operations: normalization, validation, and object creation.
Our sample subscribers.csv file contains:
email,name,plan
[email protected],Ada Lovelace,pro
[email protected],Grace Hopper,free
invalid-email,John Smith,pro
[email protected],Alan Turing,proWe want to accept valid subscribers while reporting invalid records without interrupting the entire import operation.
Step 1: Defining the Data Model
We’ll begin with a backed enum representing the available subscription plans and a readonly class to represent an imported subscriber.
<?php
enum SubscriptionPlan: string
{
case Free = 'free';
case Pro = 'pro';
}
readonly class Subscriber
{
public function __construct(
public string $email,
public string $name,
public SubscriptionPlan $plan
) {}
}Backed enums were introduced in PHP 8.1 and provide a reliable alternative to arbitrary strings. Readonly classes, available since PHP 8.2, prevent properties from being modified after initialization.
Combining these features allows us to represent a subscriber with a predictable data structure. Rather than passing unvalidated associative arrays throughout the application, we can work with typed objects.
Step 2: Creating the Processing Functions
Each processing function receives a value and returns a transformed value. This makes the functions suitable for use with PHP’s pipe operator.
The following functions normalize CSV fields, validate the incoming data, and create a Subscriber object:
<?php
function normalizeRow(array $row): array
{
return array_map(
static fn(?string $value): string => trim($value ?? ''),
$row
);
}
function validateRow(array $row): array
{
if (count($row) !== 3) {
throw new InvalidArgumentException(
'Expected exactly three fields'
);
}
[$email, $name, $plan] = $row;
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new InvalidArgumentException(
'Invalid email address'
);
}
if ($name === '') {
throw new InvalidArgumentException(
'Subscriber name is required'
);
}
if (SubscriptionPlan::tryFrom($plan) === null) {
throw new InvalidArgumentException(
'Unknown subscription plan'
);
}
return $row;
}
function createSubscriber(array $row): Subscriber
{
return new Subscriber(
email: $row[0],
name: $row[1],
plan: SubscriptionPlan::from($row[2])
);
}Each function has a clearly defined responsibility. The normalization function removes unnecessary whitespace, the validation function checks the input, and the final function converts validated data into a typed object.
The important detail is that none of these functions needs to know how the others are implemented. We can test them independently, reuse them in another import process, or replace individual operations without rewriting the entire workflow.
Step 3: Connecting Everything With the Pipe Operator
Now comes the interesting part. Instead of calling each function separately, we can connect them using the new pipe operator:
<?php
$subscriber = $row
|> normalizeRow(...)
|> validateRow(...)
|> createSubscriber(...);Reading the code from top to bottom reveals the complete processing sequence. A raw CSV record is normalized, validated, and transformed into a Subscriber object.
Unlike a framework-specific pipeline implementation, this functionality is built directly into PHP 8.5. No additional packages or custom pipeline classes are required.
Step 4: Processing the CSV File
We can now use our pipeline to process the CSV file. PHP’s native fgetcsv() function reads records incrementally, allowing us to process them without loading the entire file into memory.
Add the following code after the preceding class and function definitions to complete the importer:
<?php
$file = fopen(__DIR__ . '/subscribers.csv', 'rb');
if ($file === false) {
throw new RuntimeException(
'Unable to open CSV file'
);
}
try {
$header = fgetcsv(
$file,
separator: ',',
enclosure: '"',
escape: ''
);
if ($header !== ['email', 'name', 'plan']) {
throw new RuntimeException(
'Unexpected CSV columns'
);
}
$recordNumber = 1;
while (($row = fgetcsv(
$file,
separator: ',',
enclosure: '"',
escape: ''
)) !== false) {
$recordNumber++;
try {
$subscriber = $row
|> normalizeRow(...)
|> validateRow(...)
|> createSubscriber(...);
echo json_encode([
'email' => $subscriber->email,
'name' => $subscriber->name,
'plan' => $subscriber->plan->value
], JSON_THROW_ON_ERROR), PHP_EOL;
} catch (InvalidArgumentException $e) {
fwrite(
STDERR,
"Record {$recordNumber}: "
. $e->getMessage()
. PHP_EOL
);
}
}
} finally {
fclose($file);
}The example produces one JSON object per valid subscriber and sends validation errors to standard error. For our sample CSV file, three subscribers are accepted while the invalid email address is rejected.
We explicitly pass an empty escape parameter to fgetcsv(). Relying on its default value has been deprecated since PHP 8.4, and disabling PHP’s proprietary escaping mechanism helps maintain compatibility with standard CSV quoting conventions.
Why Is This Approach Interesting?
At first glance, the pipe operator may appear to be a minor syntax improvement. After all, we could implement the same logic using regular function calls.
However, the benefits become more apparent when working with larger processing workflows. Consider an application that needs to import product catalogs, normalize external API responses, validate incoming webhooks, or process thousands of records from different sources.
In these scenarios, a pipeline encourages developers to separate individual transformations into reusable operations. Each operation becomes easier to understand, test, and maintain.
Another advantage is that the pipeline’s structure remains largely unchanged when new requirements appear. For example, adding a duplicate-checking stage could be as simple as introducing another callable before object creation, provided the stage returns the expected data type.
This design can also improve testing. A normalization function can be tested with malformed strings, a validation function with invalid records, and an object factory with known valid inputs. Integration tests can then verify the complete sequence.
Limitations and Important Considerations
The pipe operator should not be confused with asynchronous processing, parallel execution, or an automatic error-handling mechanism. Operations are executed sequentially, and an exception interrupts the pipeline unless it is handled by surrounding application code.
The operator also passes a single value to the callable on its right. Functions requiring additional arguments must be adapted using closures. Similarly, functions that require arguments passed by reference are not supported directly in a pipe.
There are also practical considerations beyond the language feature itself. A production CSV importer should enforce upload size limits, manage duplicates, handle database transactions, and apply the appropriate encoding and validation rules. The built-in email validator, for example, may not cover every internationalized email address.
Finally, the pipe operator is available only in PHP 8.5 and later. Applications that must remain compatible with earlier PHP versions will need conventional function calls or an alternative pipeline abstraction.
Taking the Project Further
Our example can serve as the foundation for a small, reusable import component. A natural next step would be to introduce a repository that persists validated subscribers using PDO and prepared statements.
Another improvement would be to collect validation results and generate an import report containing successful records, rejected records, and the reasons for rejection. The pipeline could also be extended with transformations for phone numbers, dates, product identifiers, or other application-specific fields.
For larger applications, these operations could be organized into dedicated classes implementing __invoke(), allowing dependencies such as repositories or configuration services to be injected into individual processing stages.
The interesting point is that developers can start with a few ordinary PHP functions and gradually evolve the implementation without committing to a complex framework from the beginning.
Conclusion
PHP 8.5’s pipe operator is not revolutionary because it introduces something previously impossible. Its value lies in making an existing programming approach simpler and more expressive.
Combined with backed enums, readonly classes, first-class callables, and the standard PHP library, it offers a practical way to build lightweight, maintainable data-processing workflows.
For developers maintaining applications that regularly transform incoming data, it may be worth experimenting with the pipe operator during the next PHP 8.5 migration. Sometimes, improving code readability and reducing unnecessary complexity is a valuable feature in itself.
References
PHP Manual: Functional Operators

















![PHP #[Override]: Catching Broken Inheritance Contracts Before Production](https://phpmagazine.net/wp-content/uploads/2026/11/php-override-218x150.png)







