0

I have a head array:

Array
(
    [0] => 10
    [1] => 10
    [2] => 10
    [3] => 10
    [4] => 10
    [5] => 10
)

And my second array looks like this:

Array
(
    [0] => 1
    [1] => 7
    [2] => 3
    [3] => 1
    [4] => 1
    [5] => 7
)

Now I want to increase values in my head array by values in the second array.

Result should look like this:

Array
(
    [0] => 11
    [1] => 17
    [2] => 13
    [3] => 11
    [4] => 11
    [5] => 17
)

How can I do that?

Patrick.

Sharanya Dutta
  • 3,981
  • 2
  • 17
  • 27
coderabbit
  • 77
  • 9

3 Answers3

2

How about the following:

$result = array_map(function () {
    return array_sum(func_get_args());
}, $arr1, $arr2);

func_get_args() fetches one element from each array, array_sum() adds those two values, and array_map() creates the new array. Original idea from this answer.


Or, if you want to use a loop, try the following:

$result = array();

for($i=0,$count=count($arr1); $i < $count; $i++) {
  $result[$i] = $arr1[$i] + $arr2[$i];
}

Output:

Array
(
    [0] => 11
    [1] => 17
    [2] => 13
    [3] => 11
    [4] => 11
    [5] => 17
)

Demo

Community
  • 1
  • 1
Amal Murali
  • 75,622
  • 18
  • 128
  • 150
2

The simpler is the better.

foreach ($a1 as $index => &$value) {
    $value += $a2[$index];
}
Thomas Ruiz
  • 3,611
  • 2
  • 20
  • 33
0
for($i = 0; $i < count($headArray); $i++)
    $headArray[$i] += $secondArray[$i];
Manu
  • 922
  • 6
  • 16