Skip to content
Advertisement

Calculating Average (Mean) in PHP

I’m a bit of a beginner with PHP and am implementing a review aggregator system for a few products.

I have created the input fields and am outputting the results from these fields using this code:

JavaScript

I want to use PHP to calculate the average (mean) however the number I am using to calculate this is set to 5 as that is the total number of number fields I have. Here is the code I am using

JavaScript

The problem with this method is that sometimes the fields will not contain a value so the number to divide by would need to be 1, 2, 3 or 4 instead of 5 depending on the total number of review fields that have a value.

Essentially I need to replace “/5” with “/n” where “n” is the total number of fields with values.

Can anyone please assist?

Regards, Peter

Advertisement

Answer

I would put the values into an array, then filter out non-numeric values, and then do the calculation of the average:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement