Calculate Percentile

Calculate the nth percentile of an array using linear interpolation.

Code

General
$sorted = $arr;
sort($sorted);
$index = ($p / 100) * (count($sorted) - 1);
$lower = (int)floor($index);
$fraction = $index - $lower;
$result = $sorted[$lower] + $fraction * (($sorted[$lower + 1] ?? $sorted[$lower]) - $sorted[$lower]);
return $result;

Parameters

Array of numbers

Percentile (0-100)

Server

More PHP Snippets