Search code examples
phpmultidimensional-arraysum

Sum all elements in each subarray of a 2d array


I've got the following 2d array and I want to sum all of the elements in each subarray.

Input:

$main_array = [
    [1, 2, 3],
    [2, 4, 5],
    [8, 4, 3]
]

Desired Result:

[6, 11, 15]

I 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 
    ) 
)

Solution

  • 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);