3

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

3 Answers 3

6

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);
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.