Sum elements with the same index from two flat arrays with the same element count

arrays, php, sum

Solution

a simple approach could be

$c = array_map(function () {
    return array_sum(func_get_args());
}, $a, $b);

print_r($c);

Or if you could use PHP5.6, you could also use variadic functions like this

$c = array_map(function (...$arrays) {
    return array_sum($arrays);
}, $a, $b);

print_r($c);

Output

Array
(
    [0] => 11
    [1] => 22
    [2] => 16
    [3] => 18
    [4] => 3
)

Problem

I have two arrays: ``` $a = array(10, 2, 5, 10, 0); $b = array(1, 20, 11, 8, 3); ``` I need to sum up and get the result: ``` $c = array(11, 22, 16, 18, 3); ``` Can I do this without "foreach"?

Original source

Related problems