Skip to content

Instantly share code, notes, and snippets.

@thomas-p-wilson
Created July 30, 2013 16:13
Show Gist options
  • Save thomas-p-wilson/6114385 to your computer and use it in GitHub Desktop.
Save thomas-p-wilson/6114385 to your computer and use it in GitHub Desktop.
Calculates statistical information about an array of numbers, including upper and lower quartiles.
<?php
function array_stats(array $arr) {
sort($arr);
// Basic data
$result = array();
$result['cnt'] = count($arr);
$result['min'] = min($arr);
$result['max'] = max($arr);
$result['sum'] = array_sum($arr);
$result['avg'] = $result['sum'] / count($arr);
$result['med'] = $arr[round(count($arr) / 2)];
$result['rng'] = $arr[$result['cnt'] - 1] - $arr[0];
// Quartiles
$result['qt1'] = $arr[round( .25 * ($result['cnt'] + 1)) - 1];
$result['qt2'] = ($result['cnt'] % 2 == 0) ? (($arr[($result['cnt'] / 2) - 1] + $arr[$result['cnt'] / 2]) / 2) : ($arr[($result['cnt'] + 1) / 2]);
$result['qt3'] = $arr[round( .75 * ($result['cnt'] + 1)) - 1];
return $result;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment