Skip to content
GreenSnippets

Group an array of records by a key

Turn a flat list of associative arrays into groups keyed by a field or callback.

PHP
<?php
/**
 * @param array<int, array<string, mixed>> $rows
 * @param string|callable $key
 * @return array<string|int, array<int, array<string, mixed>>>
 */
function groupBy(array $rows, string|callable $key): array
{
    $groups = [];
    foreach ($rows as $row) {
        $groupKey = is_callable($key) ? $key($row) : $row[$key];
        $groups[$groupKey][] = $row;
    }
    return $groups;
}

Example / expected output

Output
groupBy($orders, 'status'); // ['paid' => [...], 'open' => [...]]

How it works

A single pass builds the groups and keeps each group in input order. Accepting a callable as the key makes the helper reusable for computed groupings such as month or first letter.