Skip to content

Instantly share code, notes, and snippets.

@patelnwd
Last active October 4, 2018 08:40
Show Gist options
  • Save patelnwd/0893bc6d4a30339a2ae98ee5da6f4b43 to your computer and use it in GitHub Desktop.
Save patelnwd/0893bc6d4a30339a2ae98ee5da6f4b43 to your computer and use it in GitHub Desktop.
This function calculates percentile value for given data set and percentile. Similar to MS excel =PERCENTILE(data,k) function.
<?php
function percentile_as_excel($data, $percentile){
if( 0 <= $percentile && $percentile <= 1 ) {
$p = $percentile;
}else {
return "";
}
$count = count($data);
$allindex = ($count-1)*$p;
$intvalindex = intval($allindex);
$floatval = $allindex - $intvalindex;
sort($data);
if(!is_float($floatval)){
$result = $data[$intvalindex];
}else {
if($count > $intvalindex+1)
$result = $floatval*($data[$intvalindex+1] - $data[$intvalindex]) + $data[$intvalindex];
else
$result = $data[$intvalindex];
}
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment