5

I have a array like this

 array(
      45=>5,
      42=>4.9,
      48=>5,
      41=>4.8,
      40=>4.9,
      34=>4.9,
      .....
      )

Here index is userid and value is his score.

Now what i want is to achieve percentile for on user for example percentile of 45,48 would be 99 and 42,40,34 would be 97 and 41 would be 94.

How i can achieve this?

j0k
  • 22,600
  • 28
  • 79
  • 90
Ajay Kadyan
  • 1,081
  • 2
  • 13
  • 36

2 Answers2

10
  1. Sort the array based on the "score", ascending
  2. Percentile = (Index of an element in the sorted array ) * 100 / (total elements in the array)

Example:

<?php
$array = array(
      45=>5,
      42=>4.9,
      48=>5,
      41=>4.8,
      40=>4.9,
      34=>4.9,
      );

print("Unsorted array:<br/>");
print_r($array);
arsort($array);
print("<br/>");
print("Sorted array:<br/>");
print_r($array);
print("<br/>");

$i=0;
$total = count($array);
$percentiles = array();
$previousValue = -1;
$previousPercentile = -1;
foreach ($array as $key => $value) {
    echo "\$array[$key] => $value";
    if ($previousValue == $value) {
    $percentile = $previousPercentile;
    } else {
    $percentile = 99 - $i*100/$total;
    $previousPercentile = $percentile;
    }
    $percentiles[$key] = $percentile;
    $previousValue = $value;
    $i++;
}

print("Percentiles:<br/>");
print_r($percentiles);
print("<br/>");

?>
Sameer
  • 4,379
  • 1
  • 23
  • 23
1

It can be done a lot easier

function procentile($arr, $percentile=0.95){
    sort($arr);
    return $arr[round($percentile * count($arr) - 1.0-$percentile)];
}
Gustav
  • 2,902
  • 1
  • 25
  • 31
  • If there are multiple elements in the array having the same value, this code will assign a different percentile number to each of those elements. – Sameer Feb 24 '15 at 04:35
  • @Sameer I agree with you. Do you have any suggestion on how to bypass this? – EnexoOnoma Jan 02 '17 at 03:28