Find percentiles using array in php

I have an array like this

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

Here is the index userid, and the value is its rating.

Now what I want is the achievement of the percentile for the user, for example, the percentile of 45.48 will be 99 and 42,40,34 will be 97 and 41 will be 94.

How can i achieve this?

+5
source share
2 answers
  • Array sorting based on "grade", ascending
  • Percentile = (index of the 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/>");

?>
+7
source

It can be made much simpler.

function procentile($arr, $percentile=0.95){
    sort($arr);
    return $arr[round($percentile * count($arr) - 1.0-$percentile)];
}
+1
source

All Articles