Calculating Weighted Average in PHP code

Ok I need help with calculating weighted average in php

Here is the breakdown

Weight / Factor Number
35% = 1000
15% = 2000
30% = 100
10% = 90
5% = 100
5% = 3120

35% = 1000
This represents customers five star rating system, where averaged 5 star rating will equal 1000 which equals 35% of grade

15% = 2000
This represents number of calls made, where 2000 calls made will equal 15% of grade but any more calls after that will be of no effect to grade

30% = 100
This represents a percentage to a set goal, where 100% means they have achieve the set goal or target which is 30% of their grade

10% = 90
This represents a time factor (90 days maximum), where for everyday on task it adds to the grade. 90 days on task will represent 10% of grade

5% = 100
for every new customer enrolled, (100 customers maximum) adds up to 5% of grade

5% = 3120
This is a pass or fail background check grade, where pass give five percent of grade and fail get no 5% of grade.

The normal weighted average calculation = 850
(35×1000+15×2000+30×100+10×90+5×100+5×3120) / (35+15+30+10+5+5) = 850

I need this to be done in php. Any help please.

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
$data = array(
    35 => 1000,
    15 => 2000,
    30 => 100,
    10 => 90,
    **5 => 100,**
    **5 => 3120**
);

Danger, Will Megazoid, Danger!

(You’re overwriting one of the keys!)

Starlion thank you for your comment, but what you mean Megazoid is overwriting one of the keys.

An array can only hold 1 value at a given key.

This code puts 1000 into the key “35”, 2000 into the key “15”, etc. Except until you get to the end. It puts 100 into the key 5, and then puts 3120 into the key 5, meaning the 100 disappears and you do not get a second entry for 5.

There are a couple of ways to work around it. To use megazoid’s own code as a basis, here’s what I would do.

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

$dividend = 0;
$divisor = 0;

foreach($data as $value){
    $dividend += ($value[0] * $value[1]);
    $divisor += $value[0];
}

$average = $dividend / $divisor;

echo $average;

This code produces the result 850.

1 Like

Thank you, I will try this. You guys are very helpfully.

Indeed. Missed that, my bad

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.