Best method for sum two arrays [closed]
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
)
Try like
$c = array();
foreach (array_keys($a + $b) as $key) {
$c[$key] = $a[$key] + $b[$key];
}
There's no way you can do that without the "foreach" as you asked for, you need to loop on both arrays to get the respective values.
A function using the foreach would be :
function sum_arrays($array1, $array2) {
$array = array();
foreach($array1 as $index => $value) {
$array[$index] = isset($array2[$index]) ? $array2[$index] + $value : $value;
}
return $array;
}
Now you just need to do :
$c = sum_arrays($a, $b);
$c = array();
for($i=0;$i<count($a);$i++) {
$c[$i] = $a[$i]+$b[$i];
}