$result = array_map("array_sum", $a, $b);
Sum two array rows in PHP on a single line
Question
I remember once I came across some website where sum of 2 arrays items was performed on a single line using array_sum and array_map functions. Does anyone know how to do that?
$a=array(1,2,3,4,5);
$b=array(0,1,0,1,0);
$result=compoundedSinlgeLineFunction($a,$b);
$result=array(1,3,3,5,5); //this is what we get
Solution 2
OTHER TIPS
I found I might need to sum up 3 numbers as well, so I did that this way, but it's essentially the same as the solution above
$z = array_map('sum', $z, $y, $x);
function sum($x, $y, $z=NULL){
if($z) return $x + $y + $z;
else return $x + $y;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow