Search code examples
phpsumproduct

How do you do sumproduct in PHP?


A B
1 0.72 97.29
2 0.72 67.68
3 0.72 66.97
4 0.72 67.57
5 0.72 67.80
6 0.72 94.71
7 0.72 136.23
8 0.72 146.77
9 0.72 139.06
10 0.72 95.39
11 0.35 58.66
12 0.20 48.90
13 0.05 37.07
14 0.05 61.31
15 0.20 95.26
16 0.35 140.80
17 0.72 228.09
18 0.72 318.25
19 0.72 407.95
20 0.72 413.11
21 0.72 409.11
22 0.72 394.49
23 0.72 300.57
24 0.72 162.24

I need to work out this spreadsheet formula =SUMPRODUCT(A1:A24,B1:B24) in PHP.

This is what I tried (but I think my formula is incorrect)

$a = array( 0.72, 0.72, 0.72, 0.72, 0.72, 0.72, 0.72, 0.72, 0.72, 0.72, 0.35, 0.20, 0.05, 0.05, 0.20, 0.35, 0.72, 0.72, 0.72, 0.72, 0.72, 0.72, 0.72, 0.72 );
$b = array( 97.29, 67.68, 66.97, 67.57, 67.80, 94.71, 136.23, 146.77, 139.06, 95.39, 58.66, 48.90, 37.07, 61.31, 95.26, 140.80, 228.09, 318.25, 407.95, 413.11, 409.11, 394.49, 300.57, 162.24 );

$a_total = 0;
$b_total = 0;

foreach( $a as $row ) {
    $a_total += $row;
}
foreach( $b as $row ) {
    $b_total += $row;
}

$sumproduct = $a_total * $b_total;

Solution

  • You're adding all the rows in each range and multiplying the result. That's not what SUMPRODUCT does.

    You should be multiplying the corresponding elements from each array and totalling the results:

    $a = array( 0.72, 0.72, 0.72, 0.72, 0.72, 0.72, 0.72, 0.72, 0.72, 0.72, 0.35, 0.20, 0.05, 0.05, 0.20, 0.35, 0.72, 0.72, 0.72, 0.72, 0.72, 0.72, 0.72, 0.72 );
    $b = array( 97.29, 67.68, 66.97, 67.57, 67.80, 94.71, 136.23, 146.77, 139.06, 95.39, 58.66, 48.90, 37.07, 61.31, 95.26, 140.80, 228.09, 318.25, 407.95, 413.11, 409.11, 394.49, 300.57, 162.24 );
    
    $sumProduct = 0;
    
    for( $i = 0; $i<count($a); $i++ ) {
        $sumProduct += ($a[$i]*$b[$i]);
    }
    
    echo $sumProduct;
    

    See https://3v4l.org/hkFhf

    Of course, this is just one of the options for SUMPRODUCT. See the Microsoft docs for more options for SUMPRODUCT