php
38 lines · 6 steps
Grouping records with array_reduce in PHP
A small Collection helper folds flat record arrays into keyed buckets using array_reduce.
Explained by
highlit
1<?php
2
3namespace App\Support;
4
5final class Collection
6{
7 public static function groupBy(array $records, string $key): array
8 {
9 return array_reduce(
10 $records,
11 static function (array $groups, array $record) use ($key): array {
12 $bucket = $record[$key] ?? '__null__';
13 $groups[$bucket][] = $record;
14
15 return $groups;
16 },
17 []
18 );
19 }
20
21 public static function groupByCallback(array $records, callable $resolver): array
22 {
23 return array_reduce(
24 $records,
25 static function (array $groups, $record) use ($resolver): array {
26 $groups[$resolver($record)][] = $record;
27
28 return $groups;
29 },
30 []
31 );
32 }
33
34 public static function countByStatus(array $orders): array
35 {
36 return array_map('count', self::groupBy($orders, 'status'));
37 }
38}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1array_reduce with an array accumulator turns a flat list into a keyed structure in one pass.
- 2Accepting a callable resolver makes the same fold reusable for any grouping rule.
- 3Composing small helpers like groupBy lets aggregates like counts be expressed declaratively.
Related explainers
php
<?php class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
Intermediate
8 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
php
<?php namespace App\Services;
Building a cached daily leaderboard in Laravel
caching
aggregation
eager-loading
Intermediate
9 steps
php
<?php final class RotatingFileLogger {
How a rotating file logger works in PHP
logging
file-rotation
io
Intermediate
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/grouping-records-with-array_reduce-in-php-explained-php-ed34/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.