Add values from the same PHP array

Asked

Viewed 905 times

-1

It seems to be simple but could not, I would like to add the following array (are two arrays within one, it is divided 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;

  • 1

    Now describe, please, what happened for the first to turn the second.

  • 1

    I didn’t quite understand the problem or the doubt

  • I appreciate the answers, are two array within one, I would like to add the two to become only one, got with the function I marked as response.

2 answers

1

If the idea is to add together the elements of array internal element by element, so just do:

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

So, by having the 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
)

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

0


Thanks for all your help, I got it 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);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.