Sum two arrays by index using php

You can use array_map and array_sum functions:

$sum = array_map(‘array_sum’, array_map(null, $array1, $array2));

ex:

<?
$a = array(1, 2, 3, 4, 5);
$b=array(5,4,3,2,1);

$sum = array_map(‘array_sum’, array_map(null, $a, $b));

print_r ($sum);
?>

Output:

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

One Response to “Sum two arrays by index using php”

  1. Nice snippet of code (I’m still a newb), found it very useful :D

Discussion Area - Leave a Comment