Get an average number with PHP.

In this example, we are going to show you how to calculate an “average number” using PHP.

Although this does require some basic math, PHP’s inbuilt functions do make it a little easier.

For example, let’s say that we have a PHP array that contains various numbers:

//Our array, which contains a set of numbers.
$array = array(1, 7, 9, 3, 20, 12, 2, 9);

//Calculate the average.
$average = array_sum($array) / count($array);

//Print out the average.
echo $average;

If you run the code above, you will see that the answer is 7.875.

To round that number up, we can use the ceil function like so:

//Our average is 7.875
$average = 7.875;

//Round it up.
$averageRounded = ceil($average);

A full example:

//Our array, which contains a set of numbers.
$array = array(1, 7, 9, 3, 20, 12, 2, 9);

//Calculate the average and round it up.
$average = ceil( array_sum($array) / count($array) );

//Print out the average.
echo $average;

As you can see, it’s actually pretty simple.

An explanation of the code above:

  1. We have an array that contains a set of numbers.
  2. We add those numbers together using the array_sum function.
  3. After that, we count how many numbers are in our “set” by using the count function.
  4. Finally, we divide the sum by the count and then round the result up using the ceil function.

This is by far the best way to calculate an average number in PHP. By putting our numbers into an array, we can count the size of that array instead of manually specifying the size of the set.

If you had to manually calculate the average, it would look something like this:

//Our numbers.
$num1 = 1;
$num2 = 43;
$num3 = 23;

//How many numbers are in our set.
$numbersInSet = 3;

//Get the sum of those numbers.
$sum = $num1 + $num2 + $num3;

//Calculate the average by dividing $sum by the
//amount of numbers that are in our set.
$average = $sum / $numbersInSet;

As you can, this example is far more complicated as you have to do the sum and then manually specify how many numbers are in the set.