Table of Contents

PHP RFC: Add array_group function

Introduction

This RFC is to implement a new function to PHP that upgrades the functionality of array_column to group similar results that share the same index_key into a multidimensional array. the current behavior of array_column is to return a single result and ignore the rest of the results that share the same index.

Proposal

This RFC is to add a new function called array_group

array_group(array $array, int|string|null $column_key, int|string|null $index_key = null)

The current behavior is when you have multiple elements share the same key, it will be overwritten. let's assume that we have the following.

<?php
 
$array = [
    ['id' => 1, 'name' => 'hassan'],
    ['id' => 2, 'name' => 'sara'],
    ['id' => 3, 'name' => 'selim'],
    ['id' => 4, 'name' => 'chris'],
    ['id' => 5, 'name' => 'sara'],
];

when we use array_column with this the output will be

print_r(array_column($array, null, 'name'));
Array
(
    [hassan] => Array
        (
            [id] => 1
            [name] => hassan
        )
 
    [sara] => Array
        (
            [id] => 5
            [name] => sara
        )
 
    [selim] => Array
        (
            [id] => 3
            [name] => selim
        )
 
    [chris] => Array
        (
            [id] => 4
            [name] => chris
        )
 
)

The RFC implements a new function called array_group to group the results in an indexed array to group all the similar elements, so we can use :

print_r(array_group($array, null, 'name'));
Array
(
    [hassan] => Array
        (
            [0] => Array
                (
                    [id] => 1
                    [name] => hassan
                )
 
        )
 
    [sara] => Array
        (
            [0] => Array
                (
                    [id] => 2
                    [name] => sara
                )
 
            [1] => Array
                (
                    [id] => 5
                    [name] => sara
                )
 
        )
 
    [selim] => Array
        (
            [0] => Array
                (
                    [id] => 3
                    [name] => selim
                )
 
        )
 
    [chris] => Array
        (
            [0] => Array
                (
                    [id] => 4
                    [name] => chris
                )
 
        )
 
)

Backward Incompatible Changes

No backward incompatible breaks.

Proposed PHP Version(s)

Next PHP 8.x, currently PHP 8.2.

RFC Impact

To Existing Extensions

Standard ext

Proposed Voting Choices

Yes/No vote.

Voting

Started at : 2021-12-21 Ends at : 2022-01-04

Add array_group function to PHP
Real name
Yes
No
 
 
 
 
 
 
 
 
 
Final result:
0
19

Implementation

Implementing array_group function