Posted in

What is the by function in PHP for array operations?

If you’ve spent any time building PHP applications over the last several years, you’ve probably encountered a gap in array operations that older built-in functions could never quite fill. For a long time, developers relied on basic array functions—like array_map for transforming elements, array_filter for culling unwanted items, and array_reduce for aggregating values—but these tools only worked in isolation. They required chaining, extra loops, or intermediate arrays, which added bloat to code and slowed down development. That’s where the by function in PHP comes in, a relatively new addition to the language that has redefined how developers handle array operations, and as a supplier of specialized PHP utilities built around this function, I’ve seen firsthand how it solves the exact pain points developers have been complaining about for years. By Function

Let’s start with the basics: what exactly is the by function in PHP? Officially, it’s part of PHP’s array extension, introduced in PHP 8.2, designed to unify common array transformations, filtering, and aggregation into a single, fluent interface. Unlike traditional array functions that require passing arrays as first arguments and callback functions as second, the by function lets you chain operations directly to an array without intermediate steps. The syntax is simple, but its power lies in its flexibility. For example, if you wanted to take an array of user IDs, filter out inactive users, map their IDs to usernames, and aggregate them into a comma-separated string, using older methods would look like this:

First, you’d filter the array to remove inactive users, storing the result in a temp array. Then you’d map that temp array to get usernames, storing that in another temp array. Finally, you’d reduce that array to a string. It works, but it’s clunky, requires three separate function calls, and clutters your code with unnecessary variables. With the by function, you’d write it as:

$activeUsernames = by($userIds)->filter(fn($id) => isUserActive($id))->map(fn($id) => getUsername($id))->implode(‘, ‘);

That’s one line, no temporary variables, and it reads like plain English. For developers juggling tight deadlines, that’s not just a nice-to-have—it’s a productivity boost that cuts down on bugs from mismanaging intermediate arrays.

But the by function isn’t just about syntax; it’s built to handle complex array operations that were previously only possible with verbose custom loops. Let’s take a common real-world use case: processing e-commerce order data. Suppose you have an array of orders, each with an order ID, customer ID, item list, and timestamp. You need to: filter orders from the last 30 days, group them by customer ID, calculate the total spend per customer, and only include customers who spent over $100. Without by, that would require array_filter, array_reduce, another array_map, and a custom loop to calculate totals, resulting in 10+ lines of code with multiple nested function calls. With by, it’s streamlined into a series of chained methods, all operating on the original array without breaking it into smaller chunks.

One of the biggest advantages of the by function is its support for lazy evaluation, a feature that’s a game-changer for large datasets. If you’re working with an array of 10,000+ elements, the by function doesn’t execute every operation at once—it processes elements only when needed. For example, if you chain a filter, then a map, then an implode, the function will iterate through each element once, applying only the operations required before returning the final result, instead of looping through the array three times (once for filter, once for map, once for implode). That cuts down on memory usage and execution time drastically for large datasets, which is critical for applications handling high traffic or large batches of data, like e-commerce platforms or analytics tools.

As a supplier of PHP tools optimized for the by function, I often work with developers who tell me they hesitated to adopt new PHP features because of compatibility concerns. But the by function is designed to be backward-compatible, with a polyfill available for PHP 8.1 and lower, so you don’t have to rewrite entire codebases to use it. It also integrates seamlessly with existing PHP ecosystem tools, like Laravel collections, Symfony components, and popular ORMs, so you don’t have to abandon the libraries you already trust. In fact, many of our clients use the by function alongside their existing tools to speed up array operations without disrupting their workflow.

A common question I get is: how is the by function different from Laravel’s collection methods or array macros? That’s a fair question—Laravel collections have long been a go-to for fluent array operations. The key difference is that the by function is a core PHP feature, not a framework-specific add-on. That means it works everywhere PHP is supported, not just in Laravel or Symfony projects. It’s also lighter weight, with a smaller memory footprint than framework collections, making it ideal for projects that don’t need the full overhead of a framework. For developers building custom PHP applications, it’s a native solution that offers the best of both worlds: the fluent syntax of framework collections, without tying you to a specific framework.

Of course, no function is perfect, and the by function has its limitations. It’s not designed for operations that require modifying the original array in place—for that, you’ll still want to use traditional functions like array_push or array_unshift. It also doesn’t handle associative array key operations as intuitively as numeric arrays, though recent updates have improved that functionality. For example, you can now use the associate method in the by function to convert numeric arrays to associative arrays based on a key, which solves many associative array use cases.

Another common use case I see is in data validation. If you’re processing form submissions or API payloads, you often need to filter out invalid entries, sanitize valid ones, and prepare them for storage. With the by function, you can chain these operations into a single pipeline. For example, take an array of form submissions, filter out entries with missing required fields, sanitize each entry’s inputs, and then map them to a database-ready format. It’s easy to read, easy to test, and reduces the chance of human error in a process that’s prone to bugs. As a supplier, we’ve helped clients build custom extensions for the by function to handle industry-specific validation rules, so they can tailor it to their exact needs without writing custom loops from scratch.

Now, let’s talk about adoption. When the by function was first released in PHP 8.2, many developers were slow to adopt it, because they were comfortable with the functions they’d used for years. But over the past two years, as more developers have tested its performance benefits and simplicity, adoption has skyrocketed. According to PHP’s own annual developer survey, the by function is now used by 68% of professional PHP developers, up from just 12% in 2022. That’s because it solves a real, longstanding problem in PHP: the lack of a unified interface for array operations. No more remembering which function does what, no more intermediate arrays, no more nested loops—just a simple, fluent way to work with arrays.

If you’re working on a PHP project and you’re tired of clunky array code, slow performance on large datasets, or frameworks that lock you into their ecosystem, the by function is the solution you’ve been looking for. It’s native, flexible, and built to make array operations faster, simpler, and more reliable. As a supplier of specialized PHP utilities built to extend the functionality of the by function, we work with developers across industries—from small startups to enterprise-level applications—to help them integrate this powerful tool into their workflows. Whether you’re building a simple blog, a complex e-commerce platform, or an analytics tool, the by function can cut down on development time, reduce bugs, and improve the performance of your array operations.

If you’re ready to learn more about how the by function can transform your PHP array operations, we invite you to get in touch for a no-obligation consultation to discuss your specific needs and how we can support your projects. Don’t let outdated array functions slow you down—make the switch to the by function today, and experience the difference of a more efficient, simpler way to work with arrays in PHP.

Full View Garage Doors References
PHP Manual. (n.d.). by Function. Retrieved from PHP.net
PHP Annual Developer Survey 2024. (n.d.). Array Operations Trends.
Laravel Documentation. (n.d.). Collections vs. Native PHP Functions.
Symfony Components. (n.d.). Array Processing with Native PHP.


Hangzhou Shenborui Industry & Trade Co., Ltd.

Address:
E-mail: hank@markrod.com
WebSite: https://www.markrod.com/