Home > OS >  Calculating Average (Mean) in PHP
Calculating Average (Mean) in PHP

Time:02-17

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 >Review 1: '; the_field('review1'); '</div>';}
{ echo '<div >Review 2: '; the_field('review2'); '</div>';}
{ echo '<div >Review 3: '; the_field('review3'); '</div>';}
{ echo '<div >Review 4: '; the_field('review4'); '</div>';}
{ echo '<div >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

CodePudding user response:

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

CodePudding user response:

$items = ['1','2','7','',''];

$average = calculateAverage($items);

echo $average;

function calculateAverage($items)
{
    $total = 0;
    $count = 0;

    foreach($items as $item)
    {
        if(is_numeric($item))
        {
            $total  = $item;
            $count  ;
        }
    }

    return $total / $count;
}

If the number is empty, it will not add the number to the devider

  • Related