Merging duplicate values into multi-dimensional array in PHP

In PHP, you can merge duplicate values into a multi-dimensional array by grouping elements based on a common key. This technique helps organize data and eliminate redundant entries by creating sub-arrays for each unique key value.

Example

Here's how to group array elements by their 'hobby' field −

<?php
$my_arr = array(
    array('Age'=>23, 'name'=>'Joe', 'hobby'=>'Cycling'),
    array('Age'=>26, 'name'=>'Hannah', 'hobby'=>'Rowing'),
    array('Age'=>30, 'name'=>'Dev', 'hobby'=>'Cycling'),
    array('Age'=>30, 'name'=>'Dev', 'hobby'=>'Cycling')
);

foreach($my_arr as $entry => $vals)
{
    $new_vals[$vals['hobby']][]=$vals;
}

echo "The grouped array elements are:<br>";
print_r($new_vals);
?>
The grouped array elements are:
Array
(
    [Cycling] => Array
        (
            [0] => Array
                (
                    [Age] => 23
                    [name] => Joe
                    [hobby] => Cycling
                )

            [1] => Array
                (
                    [Age] => 30
                    [name] => Dev
                    [hobby] => Cycling
                )

            [2] => Array
                (
                    [Age] => 30
                    [name] => Dev
                    [hobby] => Cycling
                )

        )

    [Rowing] => Array
        (
            [0] => Array
                (
                    [Age] => 26
                    [name] => Hannah
                    [hobby] => Rowing
                )

        )

)

How It Works

The code iterates through the original array using a foreach loop. For each element, it uses the 'hobby' value as a key in the new array $new_vals. The square brackets [] append each matching element to the sub-array for that hobby, effectively grouping all elements with the same hobby together.

Conclusion

This method efficiently organizes multi-dimensional arrays by creating groups based on shared field values. It's particularly useful for categorizing data and reducing redundancy in array structures.

Updated on: 2026-03-15T09:02:11+05:30

853 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements