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 [0]=>6, [1]=>11, [2]=>15.

Array 
( 
[0] => Array 
       ( 
         [0] => 1 
         [1] => 2 
         [2] => 3 
       ) 
[1] => Array 
       ( 
         [0] => 2 
         [1] => 4 
         [2] => 5 
       ) 
[2] => Array 
       ( 
         [0] => 8 
         [1] => 4 
         [2] => 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 
( 
    [0] => Array 
    ( 
        [1] => 6 
    ) 
    [1] => Array 
    ( 
        [1] => 11
    ) 
    [2] => Array 
    ( 
        [1] => 15 
    ) 
)

I’m expecting the array structure as follows.

Array 
( 
    [0] => 6

    [1] => 11

    [2] => 15

)

Thanks in advance!

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

Leave a Reply