# Summing of all elements in the sub array – PHP

I’ve got the following array as \$main_array .Wanted to sum up all the elements in the sub array such as =>6, =>11, =>15.

``````Array
(
 => Array
(
 => 1
 => 2
 => 3
)
 => Array
(
 => 2
 => 4
 => 5
)
 => Array
(
 => 8
 => 4
 => 3
)
)
``````

Tried the following code.

``````foreach (\$main_array as \$key => \$value)
\$main_array[\$key] = Array('1'=>array_sum(\$value));
print_r(\$main_array);
``````

But the array structure I got was,

``````Array
(
 => Array
(
 => 6
)
 => Array
(
 => 11
)
 => Array
(
 => 15
)
)
``````

I’m expecting the array structure as follows.

``````Array
(
 => 6

 => 11

 => 15

)
``````

## Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

### Solution 1

When you’re calling Array function you’re explicitly making an array so you have to remove this from `Array('1'=>array_sum(\$value));`

This is how your code should look like

``````foreach (\$main_array as \$key => \$value)
\$main_array[\$key] = array_sum(\$value);
``````

### Solution 2

Try this:

``````  foreach (\$main_array as \$key => \$value)
\$main_array[\$key] = array_sum(\$value);
``````

That is, place the sum directly in the top level array.

### Solution 3

Call `array_sum()` on every row in your input array. `array_map()` makes this operation expressive, concise, and doesn’t require any new variables to be declared.

Code: (Demo)

``````\$array = [
[1, 2, 3],
[2, 4, 5],
[8, 4, 3],
];

var_export(array_map('array_sum', \$array));
``````

Output:

``````array (
0 => 6,
1 => 11,
2 => 15,
)
``````

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0