Skip to content
Advertisement

PHP multiply column of multidimensional array and get sum of result

Very basically you suppose I have this arrays:

$a = [1,2,3];
$b = [4,5,6];

and now I want to Multiply the numbers of columns, for example:

1*4
2*5
3*6

and get sum multiply of all calculation, for example:

4+10+18 = 32

I need to get this result, I can’t implementing this scenario with array_map or array_reduce, using two foreach return wrong result for me

Advertisement

Answer

Try This..

$total = 0;
for($i = 0; $i < count($a); $i++) {
  $total += $a[$i] * $b[$i];
}

echo $total;
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement