Oihana PHP

groupBy.php

Table of Contents

Functions

groupBy()  : array<int|string, array<int|string, mixed>>
Groups the items of an array into buckets keyed by a computed value.

Functions

groupBy()

Groups the items of an array into buckets keyed by a computed value.

groupBy(array<int|string, mixed> $items, callable $keyer) : array<int|string, array<int|string, mixed>>

The $keyer callback is invoked as fn( $value , $key ) for every entry and must return the group key. Non int|string keys are cast to string. Original keys are preserved inside each bucket.

Parameters
$items : array<int|string, mixed>

The array to group.

$keyer : callable

The grouping callback: fn( $value , $key ): int|string.

Tags
example
use function oihana\core\arrays\groupBy;

$people =
[
    [ 'name' => 'Alice' , 'city' => 'Paris'  ] ,
    [ 'name' => 'Bob'   , 'city' => 'Lyon'   ] ,
    [ 'name' => 'Carol' , 'city' => 'Paris'  ] ,
];

$byCity = groupBy( $people , fn( $p ) => $p[ 'city' ] ) ;
// [ 'Paris' => [ 0 => Alice, 2 => Carol ] , 'Lyon' => [ 1 => Bob ] ]
author

Marc Alcaraz (ekameleon)

since
1.0.9
Return values
array<int|string, array<int|string, mixed>>

An associative array of groupKey => [ originalKey => value, … ] buckets.

On this page

Search results