Search code examples
phpmathformularanking

Rank Average with PHP


In Excel there's a function Rank Average (see documentation).

I wish to do the same in PHP. Looking online, I find a lot of ranking solutions, but not a lot of those take duplicates into account and when they do, the result I get is not the same as Excel is giving me at all. It's very important it does though.

Ideally, what I'd need is a function that requires a score and array to compare it with, and give me the rank for it.

Example with some actual date from Excel:

$array = array(5.80,6.00,6.00,5.60,3.20,3.00,3.60,5.70,3.60,1.90,5.00,5.80,3.00,3.80,5.00,3.00,6.00,5.70,5.00,4.90,4.20,3.60,5.00,4.90,4.90,3.00
3.30,4.80,4.60,4.10,4.70,6.00,3.30,4.30,4.30,3.00,3.10,6.00,1.90,3.80,5.00,2.00,2.80,3.00,4.20,3.00,5.50,6.00,5.00,5.00);

$score1 = 5.80;
$score2 = 6.00;

$rank1 = rankAvg($score1, $array); //should return 7.5
$rank2 = rankAvg($score2, $array); //should return 3.5

Solution

  • function rank_avg($value, $array, $order = 0) {
    // sort  
      if ($order) sort ($array); else rsort($array);
    // add item for counting from 1 but 0
      array_unshift($array, $value+1); 
    // select all indexes vith the value
      $keys = array_keys($array, $value);
      if (count($keys) == 0) return NULL;
    // calculate the rank
      return array_sum($keys) / count($keys);
    }
    
    echo rank_avg(25, array(20,23,25,27,29), 1);