IT & Programming

Calculate average with PHP

  • How to calculate average with PHP.
  • Custom PHP Function to calculate average.
  • Get average with custom PHP function.

This function accepts array parameter. The array includes the number values.

Function

function average($numbers) {

	$a = $numbers;
	$b = 0;
	$c = 0;
	$d = 0;

	foreach ($a as $b) {
	
		$c = $c + $b;
		$d++;
	}

	return number_format($c/$d,0);
}

Calling The Function

$numbers = array(1,2,3,4,5);

echo average($numbers);

Output

3

Comments

  1. Matija Corbic January 01, 2013

    Great work, thx a lot!

Leave A comment

Email address is optional and will not be published. Only add email address if you want a reply from blog author.
Please fill required fields marked with *