find average number from array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
GeXus
Forum Regular
Posts: 631
Joined: Sat Mar 11, 2006 8:59 am

find average number from array

Post 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!
User avatar
Burrito
Spockulator
Posts: 4715
Joined: Wed Feb 04, 2004 8:15 pm
Location: Eden, Utah

Post 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;
}
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

Code: Select all

function getAverage($array)  {
   return (array_sum($array) / count($array));
}
;)
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

You may want to throw number_format() at it as well.
Post Reply