← Back to all snippets
PHP

Group Associative Array by Key

Efficiently group an array of associative arrays into a new array where items are grouped under keys derived from a specified common field.

function groupArrayByKey(array $array, string $key): array {
    $grouped = [];
    foreach ($array as $item) {
        if (isset($item[$key])) {
            $grouped[$item[$key]][] = $item;
        }
    }
    return $grouped;
}

$products = [
    ['id' => 1, 'name' => 'Laptop', 'category' => 'Electronics', 'price' => 1200],
    ['id' => 2, 'name' => 'Keyboard', 'category' => 'Electronics', 'price' => 75],
    ['id' => 3, 'name' => 'Desk Chair', 'category' => 'Furniture', 'price' => 300],
    ['id' => 4, 'name' => 'Monitor', 'category' => 'Electronics', 'price' => 400],
    ['id' => 5, 'name' => 'Table Lamp', 'category' => 'Furniture', 'price' => 50]
];

$groupedByCategory = groupArrayByKey($products, 'category');
// print_r($groupedByCategory);
/*
Output:
Array
(
    [Electronics] => Array
        (
            [0] => Array ( [id] => 1, [name] => 'Laptop', [category] => 'Electronics', [price] => 1200 )
            [1] => Array ( [id] => 2, [name] => 'Keyboard', [category] => 'Electronics', [price] => 75 )
            [2] => Array ( [id] => 4, [name] => 'Monitor', [category] => 'Electronics', [price] => 400 )
        )
    [Furniture] => Array
        (
            [0] => Array ( [id] => 3, [name] => 'Desk Chair', [category] => 'Furniture', [price] => 300 )
            [1] => Array ( [id] => 5, [name] => 'Table Lamp', [category] => 'Furniture', [price] => 50 )
        )
)
*/
How it works: This function iterates through an array of associative arrays. For each item, it uses the value of the specified `$key` to create a new key in the `$grouped` array. If the key already exists, the current item is appended to the array associated with that key, effectively grouping all items with the same key value together.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs