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 namespace App\Support;
Locale-aware formatting with PHP's intl extension
internationalization
encapsulation
constructor-injection
Intermediate
7 steps
php
<?php namespace App\Support;
Merging query params onto a URL in PHP
url-parsing
query-strings
immutability
Intermediate
8 steps
php
<?php class ImageUploadService {
Validating file uploads safely in PHP
file-upload
input-validation
security
Intermediate
8 steps
javascript
const RATE_LIMIT = 100; const WINDOW_MS = 60 * 1000; const BLOCK_MS = 5 * 60 * 1000;
Building a rate-limiting middleware in Express
rate-limiting
middleware
closures
Intermediate
9 steps
php
<?php namespace App\View;
Building a safe HTML escaper in PHP
security
xss
escaping
Intermediate
6 steps
rust
use std::collections::HashMap; pub struct Memoizer<K, V, F> { cache: HashMap<K, V>,
A generic memoizer in Rust
memoization
generics
caching
Intermediate
6 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.