Re: [RFC] [Discussion] Add new function `array_group`

From: Date: Wed, 31 May 2023 23:19:19 +0000
Subject: Re: [RFC] [Discussion] Add new function `array_group`
References: 1 2  Groups: php.internals 
Request: Send a blank email to internals+get-120497@lists.php.net to get a copy of this message
> On 1.6.2023, at 01:13, Levi Morrison <levi.morrison@datadoghq.com> wrote: > > On Tue, May 30, 2023 at 5:35 AM Boro Sitnikovski <buritomath@gmail.com> wrote: >> >> Hello all, >> >> As per the How To Create an RFC instructions, I am sending this e-mail in order to get your >> feedback on my proposal. >> >> I propose introducing a function to PHP core named >> array_group. This function takes an array and a function and returns >> an array that contains arrays - groups of consecutive elements. This is very similar to >> Haskell's groupBy function. >> >> For some background as to why - usually, when people want to do grouping in PHP, they use >> hash maps, so something like: >> >> ``` >> <?php >> $array = [ >> [ 'id' => 1, 'value' => 'foo' ], >> [ 'id' => 1, 'value' => 'bar' ], >> [ 'id' => 2, 'value' => 'baz' ], >> ]; >> >> $groups = []; >> foreach ( $array as $element ) { >> $groups[ $element['id'] ][] = $element; >> } >> >> var_dump( $groups ); >> ``` >> >> This can now be achieved as follows (not preserving keys): >> >> ``` >> <?php >> $array = [ >> [ 'id' => 1, 'value' => 'foo' ], >> [ 'id' => 1, 'value' => 'bar' ], >> [ 'id' => 2, 'value' => 'baz' ], >> ]; >> >> $groups = array_group( $array, function( $a, $b ) { >> return $a['id'] == $b['id']; >> } ); >> ``` >> >> The disadvantage of the first approach is that we are only limited to using equality check, >> and we cannot group by, say, < or other functions. >> Similarly, the advantage of the first approach is that the keys are preserved, and elements >> needn't be consecutive. >> >> In any case, I think a utility function such as array_group >> will be widely useful. >> >> Please find attached a patch with a proposed implementation. Curious about your feedback. >> >> Best, >> >> Boro Sitnikovski >> > > I'm sorry if one of the many replies already mentioned this, but there > was a failed RFC for array_group: > https://wiki.php.net/rfc/array_column_results_grouping. Note > that I > voted against it for technical reasons (the signature was just awful, > we can do better), but I am not against the idea of adding such helper > functions in principle. Folks did mention that RFC, but nobody mentioned the rejection reasons specifically. Thank you for the information and encouragement! I was a bit scared of this one being rejected too, but still decided to give it a shot :)

« previous php.internals (#120497) next »