Page 1 of 1

find average number from array

Posted: Thu Nov 16, 2006 11:16 am
by GeXus
How would I find the average number from an array? Basically I have the following array

Code: Select all

array(5, 30, 40, 50);
Thanks!

Posted: Thu Nov 16, 2006 11:27 am
by Burrito
not sure if there is a native funciton to do that...something like this might work

/untested

Code: Select all

function arrayAverage($arr)
{
	$size = count($arr);
	$tot = 0;
	foreach($arr as $val)
		$tot += $val;
	$retval = ($tot / $size);
	return $retval;
}

Posted: Thu Nov 16, 2006 12:05 pm
by John Cartwright

Code: Select all

function getAverage($array)  {
   return (array_sum($array) / count($array));
}
;)

Posted: Thu Nov 16, 2006 1:03 pm
by RobertGonzalez
You may want to throw number_format() at it as well.