Question: I return an array of elements from a MySql table, and the array looks like this:

```
array (
  0 => 
    array (
      'name' => 'BMW',
      'amount' => '5',
    ),
  1 => 
    array (
      'name' => 'Ford',
      'amount' => '2',
    ),
  2 => 
    array (
      'name' => 'BMW',
      'amount' => '4',
    ),
  3 => 
    array (
      'name' => 'Ford',
      'amount' => '8',
    ),
  4 => 
    array (
      'name' => 'Fiat',
      'amount' => '2',
    ),
)

```

I like to merge together all arrays with the same 'name' element and add together the corresponding 'amount' elements so that the output of the above array will be:

```
array (
  0 => 
    array (
      'name' => 'BMW',
      'amount' => '9',
    ),
  1 => 
    array (
      'name' => 'Ford',
      'amount' => '10',
    ),
  2 => 
    array (
      'name' => 'Fiat',
      'amount' => '2',
    ),
)

```

Answer: 
Instead of manipulating data with PHP you can select the requested data directly with MySQL using the `GROUP BY` statement.

```
SELECT name, SUM(amount) total FROM mytable GROUP BY name

```

`SUM()` in this case is the [aggregate function](https://www.w3schools.com/sql/sql_functions.asp), others are available as well.

While looping you should be able to access the data like so:

```
echo $row['name'], $row['total'];

```
You can try 
array\_merge\_recursive();

<http://php.net/manual/en/function.array-merge-recursive.php>

and then to loop result array and sum elements.

or you use this code or I think solutions below are also very reasonable

```
$result = array();
foreach ($tab as $key => $elem){
        if (array_key_exists($elem['name'],$result)) {
            $result[$elem['name']] += $elem['amount'];
        } else {
            $result[$elem['name']] = $elem['amount'];
        }
}

```