Get the 'Average' from an array


I'm seeking some help with what is probably more PHP than elgg specific, but am not having much luck on PHP forums and...well its in the elgg environment anyway.

I have an array that is created from metadata (basicially a rating system)

$ratings = elgg_get_entities_from_metadata(array( etc etc...
        foreach ($ratings as $rating) {
        $value = $rating->rate; 

//  ->RATE has a variety of user inputs and will be 'poor' 'satisfactory' 'good' 'fantastic'
        $allratings[] = $value; 

//keep adding user ratings to the array
        $sum_ratings = array_sum($allratings) ;

// this array_sum seems to return NO value

        $count_ratings = count($allratings) ;
        $avarage_ratings = $sum_ratings/$count_ratings;
        echo "average:" . $average_ratings;

I suspect I could be making life easier by not using 'poor' 'good' etc and actually using number values?

Any hints/help greatly appreciated. Thanks,


  • You've got it right: Using integers is the way to go.

    You're asking PHP to (sorta) do the following arithmetic:

    (poor + satisfactory + good + fantastic) / 4

    That doesn't make sense as a standard mathematical expression, so PHP doesn't know what to do with it.  Also, array_sum() expects values to be integers, not strings.

    One solution is to map the string values to integers, then do the math on those integer values and map them back to the strings.  Functions you might want to check out: floor() and ceil().

  • Cool - thanks Brett :) :) :)