Forked from ischenkodv/Calculate median and average in PHP
Last active
September 18, 2016 03:53
-
-
Save prmichaelsen/685236b4ec4d321a037f36debed1e15c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function median($arr){ | |
if($arr){ | |
$count = count($arr); | |
sort($arr); | |
$mid = floor($count/2); | |
return ($arr[$mid]+$arr[$mid+1-$count%2])/2; | |
} | |
return false; | |
} | |
function average($arr){ | |
return ($arr) ? array_sum($arr)/count($arr) : false; | |
} | |
//test it out | |
$test = array( | |
array(5,2,1,3,4), | |
array(), | |
array(1) | |
); | |
foreach($test as $arr){ | |
echo 'avg: '.average($arr)."<br>"; | |
echo 'median: '.median($arr)."<br>"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment