Arrays\groupBy()

higher-order reducer terminal accepts iterable returns Closure pure
(T → int|string) → (Iterable → map)
At a glance — Group a collection by a key derived from each element. Terminal — consumes the whole source.

Creates a Closure that groups an array or iterable into buckets keyed by the result of the callback.

/**
  * @param callable(mixed):(string|int) $function
  * @return Closure(iterable<int|string, mixed>):mixed[]
  */
Arrays\groupBy(callable $function): Closure

Returned Closure

When Arrays\groupBy() is called, it returns the following Closure which can be used like a regular function.

/**
  * @param iterable<int|string, mixed> $source
  * @return mixed[]
  */
$function (iterable $source): array

Examples

Partial Application

This can be used to create a simple closure which can be used as a regular function.

$byParity = Arrays\groupBy(fn($n) => $n % 2 === 0 ? 'even' : 'odd');

print_r($byParity([1, 2, 3, 4]));
// ['odd' => [1, 3], 'even' => [2, 4]]

Curried

This can be called inline using currying.

print_r(Arrays\groupBy(fn($u) => $u['role'])([
  ['role' => 'admin', 'id' => 1],
  ['role' => 'user',  'id' => 2],
  ['role' => 'admin', 'id' => 3],
]));

Details

Arrays Functions

Releated Array grouping Functions