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
javascript
const ROLE_PERMISSIONS = { admin: ['users:read', 'users:write', 'billing:read', 'billing:write'], manager: ['users:read', 'billing:read'], member: ['users:read'],
Role-based permissions middleware in Express
authorization
middleware
rbac
Intermediate
9 steps
php
<?php namespace App\Console\Commands;
Releasing stale document locks in Laravel
artisan-command
transactions
row-locking
Intermediate
6 steps
php
<?php namespace App\Providers;
Subdomain multi-tenancy routing in Laravel
multi-tenancy
service-container
route-binding
Advanced
7 steps
php
<?php namespace App\Broadcasting;
Authorizing presence channels in Laravel
broadcasting
authorization
presence-channels
Intermediate
3 steps
php
<?php namespace App\Http\Middleware;
Resolving the current team in Laravel middleware
middleware
multi-tenancy
cookies
Intermediate
8 steps
php
<?php namespace App\Http\Controllers;
Broadcasting typing indicators in Laravel
websockets
authorization
presence-channels
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.