One of the things you have asked us in the comments is that we explain how you can calculate the mean or average in PHP of a set of numbers. So we are going to explain how we can achieve it through this article.
The first thing will be to define an array in which we will have the numbers.
$numbers = [1,2,3,4];
We could have obtained these numbers in any way. The important thing is that in the end you have left them inside the array.
The next thing will be to know how to calculate the mean or average of a set of numbers. We could say that…
The mean or average is equal to the sum of all the numbers divided by the total number of numbers we have.
So we have to figure out how to achieve those two things. On the one hand how to add all the numbers and on the other hand how to count them.
To add all the numbers we have two alternatives. The first is to go through the entire array and add the numbers.
$sum = 0;
for ($x=0;$x
Or we can rely on the array_sum()
function. This second case is much simpler, since we will simply have to pass the array as a parameter.
$sum = array_sum($numbers);
On the other hand we have to count how many numbers there are in the array. For this we are going to use the count()
function. To which we also pass the array.
$total_numbers = count($numbers);
We will only have to divide both concepts to obtain the mean or average in PHP.
$media = $sum/$total_numbers;
Although we could make it much smaller in a single sentence by writing:
$media = array_sum($numbers)/count($numbers);
I hope this example has been understood and is useful to be able to calculate the mean or average in PHP of a set of numbers.