This is a simple example on how to calculate an “average number” using PHP. Although this is just some basic Math, some of PHP’s inbuilt functions do make it a little less laborious.
For example, let’s say that we have a PHP array that contains various numbers:
<?php //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’ll see that the answer is 7.875. To round that number up, we can use the ceil function:
//Our average is 7.875 $average = 7.875; //Round it up. $averageRounded = ceil($average);
<?php //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;
See? Pretty simple!
- We have an array that contains a set of numbers.
- We add those numbers together using the array_sum function.
- We count how many numbers are in our set by using the count function.
- We round the result up using the ceil function.
Note that this is the preferred way of finding the average in PHP, simply because you don’t have to manually specify how many numbers are in your set. If you were to calculate the average in a manual fashion, it would look like this:
<?php //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 a little more tedious as you have to carry out the sum and manually specify how many numbers are in the set!