Add values from the same PHP array

-1

It seems to be simple but I could not, I would like to add the following array (there are two arrays inside one, it is split with the array_chunk):

    $arr = [
  [1, 2, 3, 4, 5],
  [6, 7, 8, 9, 0]
];

I would like the result to be this:

Array
(
    [0] => 7   // 1+6
    [1] => 9   // 2+7
    [2] => 11  // 3+8
    [3] => 13  // 4+9
    [4] => 5   // 5+0
)

Thank you in advance;

    
asked by anonymous 11.06.2018 / 18:20

2 answers

0

Thanks for the help of all, I got with the following code:

    $soma_array = array();

foreach ($producao_ as $k=>$subArray) {
  foreach ($subArray as $id=>$v) {
    $soma_array[$id]+=$v;
  }
}

print_r($soma_array);
    
11.06.2018 / 18:25
1

If the idea is to add elements from the internal array element to element, then just do:

$result = array_map(function(...$values) {
  return array_sum($values);
}, ...$arr);

So, when having array :

$arr = [
  [1, 2, 3, 4, 5],
  [6, 7, 8, 9, 0]
];

The result will be:

Array
(
    [0] => 7   // 1+6
    [1] => 9   // 2+7
    [2] => 11  // 3+8
    [3] => 13  // 4+9
    [4] => 5   // 5+0
)

It even works for any amount of arrays :

$arr = [
  [1, 2, 3, 4, 5],
  [6, 7, 8, 9, 0],
  [3, 4, 5, 6, 7],
  [2, 3, 4, 5, 6],
  [5, 6, 7, 8, 9],
  [0, 1, 2, 3, 4]
];

$result = array_map(function(...$values) {
  return array_sum($values);
}, ...$arr);

print_r($result);

// Array
// (
//     [0] => 17
//     [1] => 23
//     [2] => 29
//     [3] => 35
//     [4] => 31
// )
11.06.2018 / 18:28