Calculate Average in PHP Example

To calculate the average of numbers in PHP, we first need to add up all the item, then divide by the total number of items. In our example, we will add up the eight numbers 2, 4, 5, 3, 2, 9, 11, and 9.

First, the code example:

<?php
  $totalRatings = 2+4+5+3+2+9+11+9;
  $totalVotes = 8;
  $average = $totalRatings / $totalVotes;
  echo "Average: $average";
?>

Next, the output of the above PHP example will print the following to a web browser.

Average: 5.625

Since PHP is not strongly typed, the line of PHP code that performs the dividing of $totalRatings and $totalVotes (both integers) will correctly result in a double value.

Share and Enjoy:
  • Digg
  • DotNetKicks
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Live
  • MySpace
  • Netvibes
  • Reddit
  • StumbleUpon
You can leave a response, or trackback from your own site.

4 Responses to “Calculate Average in PHP Example”

  1. nasr says:

    hi
    i got problem with php with average
    may you help me plz?

  2. Victor Chen says:

    Can you explain the problem you are having?

  3. PGR says:

    Hey, can you help me with this?

    If I’m making a rating system with this code, and the ratings are stored in a text file, how could I count the number of ratings and add them up, like in your code?

    Please email me, thanks :)

  4. hmm says:

    I randomly found this page. Even though it’s been several months, I’ll post a reply. Just read each, add the values and follow the “tutorial” above. If you still need help, google it.

Leave a Reply