Group an array of records by a key
Turn a flat list of associative arrays into groups keyed by a field or callback.
- PHP
- GreenSnippets
- MIT
- Executed with PHP 8.2
<?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
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.
Related snippets
- JavaScript Tested
Remove duplicates from an array
Deduplicate primitives with a Set, or objects by a key or computed value, keeping the first occurrence.
- JavaScript Tested
Sort an array by multiple keys
Sort objects by one field, then break ties with another, with ascending or descending order per field.
- TypeScript Tested
Non-empty array type
Encode "at least one element" in the type so head, max and similar functions never see an empty array.
- TypeScript Tested
Generic groupBy with key inference
Group an array into a Record by a property or function while keeping the item type.

