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:

{ echo '<div class="review1">Review 1: '; the_field('review1'); '</div>';}
{ echo '<div class="review2">Review 2: '; the_field('review2'); '</div>';}
{ echo '<div class="review3">Review 3: '; the_field('review3'); '</div>';}
{ echo '<div class="review4">Review 4: '; the_field('review4'); '</div>';}
{ echo '<div class="review5">Review 5: '; the_field('review5'); '</div>';}

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

{ echo (get_field('review1')+get_field('review2')+get_field('review3')+get_field('review4')+get_field('review5'))/5;}

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:

$array = [ 123, 45, null, 17, 236 ];
// $array = [ get_field('review1'), get_field('review2'), etc. ]

$values = array_filter($array, 'is_numeric');
$result = array_sum($values) / count($values);

echo $result;   // Output:   105.25
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement