Calculating Weighted Average in PHP code

PHP implementation will depend on how your data is stored.

Here is example for simple array:

<?php
$data = array(
    35 => 1000,
    15 => 2000,
    30 => 100,
    10 => 90,
    5 => 100,
    5 => 3120
);

$dividend = 0;
$divisor = 0;

foreach($data as $percent => $value){
    $dividend += ($percent * $value);
    $divisor += $percent;
}

$average = $dividend / $divisor;

echo $average;

This script outputs 889.47368421053.

2 Likes