Created
September 1, 2022 15:18
-
-
Save guimadaleno/64fa0175f5bd8b822e2e96cb49a5f3e5 to your computer and use it in GitHub Desktop.
Calculate average and median of array values
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
<?php | |
/** | |
* Calculate average of array values | |
* @param array $array | |
* @return int $average | |
*/ | |
function array_average ($arr) | |
{ | |
$total = (int) 0; | |
$count = (int) @count($arr); | |
foreach ($arr as $value) | |
$total = $total + $value; | |
return ($total / $count); | |
} | |
/** | |
* Calculate median of array values | |
* @param array $arr | |
* @return int $median | |
*/ | |
function array_median ($arr) | |
{ | |
$count = @count($arr); | |
$middleval = floor(($count-1)/2); | |
if ($count % 2): | |
return $arr[$middleval]; | |
else: | |
$low = $arr[$middleval]; | |
$high = $arr[$middleval+1]; | |
return (($low+$high) / 2); | |
endif; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment