Skip to content

Instantly share code, notes, and snippets.

@guimadaleno
Created September 1, 2022 15:18
Show Gist options
  • Save guimadaleno/64fa0175f5bd8b822e2e96cb49a5f3e5 to your computer and use it in GitHub Desktop.
Save guimadaleno/64fa0175f5bd8b822e2e96cb49a5f3e5 to your computer and use it in GitHub Desktop.
Calculate average and median of array values
<?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