Get Thunderbird! Firefox 2

Misc. Stats For This Page

Operating Systems
Linux
Windows
Mac
Other

Browsers
Firefox
MSIE
Netscape
AOL
Safari
Opera
MSN
Search Bots
Other

Google
Web www.ckorp.net
Page loads - 2580.
This page last modified on 01 Nov 2007
Foxkeh banners for Firefox 2 Click here for your favorite eBay items
.c.a.l.c.u.l.a.t.e.p.e.r.c.e.n.t.i.l.e.
This one took me a while. I needed to calculate the percentile of a set of values for another project I was working on. Not being a mathematician, I first had to learn how to do this mathematically before I could even begin to program it. At the time, Google did not return very many results for programming a percentile function in PHP. I decided that since I took me so long to figure it out I had best post it here not only for me but for anyone else interested in doing this as well.

CalculatePercentile(ARRAY, VALUE [,PRECISION])

Function that calculates the percentile VALUE lands in when compared to the values in ARRAY. Optional thrid parameter of PRECISION is the number of decimal places to return to percentile in, defaults to 2. Returns FALSE if VALUE is out of range of ARRAY.

Here is the code:
<?php
function CalculatePercentile($list$amount){
  
// the formula used Y(p) = Y[k] + d(Y[k+1] - Y[k])
  //                  p(N+1) = k + d
  
$precision = (func_num_args() == 3) ? func_get_arg(2) : 2;
  
sort($list);
  if(
$amount <= $list[0]){
    return 
"1.00";
  }else if(
$amount >= $list[(sizeof($list)-1)]){
    return 
"99.00";
  }else{
    
$k FALSE;
    foreach(
$list as $key=>$value){
      if((
$amount >= $value) && ($amount $list[($key+1)])){
        
$k $key;
      }
    }
    if(!(
$k === FALSE)){
      
$d = (($amount/($list[$k+1]-$list[$k]))/($list[$k]/($list[$k+1]-$list[$k])));
      
$p = (((($k+1)+$d)/(sizeof($list)+1))*100);
      return 
number_format($p,$precision);
    }else{
      return 
FALSE;
    }
  }
}
?>