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

Walkthrough

Space play step click any line
Three takeaways
  1. 1array_reduce with an array accumulator turns a flat list into a keyed structure in one pass.
  2. 2Accepting a callable resolver makes the same fold reusable for any grouping rule.
  3. 3Composing small helpers like groupBy lets aggregates like counts be expressed declaratively.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Grouping records with array_reduce in PHP — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code