Karem
Karem

Reputation: 18103

PHP: calculating the average 3

Im working on a star rating (5 stars is best, 1 is bad), and i have 4 records of 4 users voted.

user1: 3
user2: 4
user3: 5
user4: 3

How can i calculate out the average of this in php?

Is it just simple math, $count = $user1 + $user2 + $user3 + $user4/4 ?

I tried:

echo round(3+4+5+3/4);

and got the number "13" which is not right

Upvotes: 0

Views: 2357

Answers (6)

mike
mike

Reputation: 5213

You have 2 options how to store the votes.
a) separately as you do now (user1: 5; user2: 3; user3: 4;...)
b) or you can aggregate the votes

You most probably implemented option a), but let me show you what option b) is about.
When you aggregate votes, for each post/article/news you store only 2 values - number of votes and average rating.
This helps you to retrieve the average rating faster and easier every time you render a page.
However when a user casts his/her vote, you need to do a little math to update the average rating.

Suppose the stored values are as follows
average rating = 3.3
number of votes = 5

If user votes 3, you need to update both average rating and number of votes like this:
new number of votes = [old number of votes] + 1 (5 + 1 = 6)
new average rating =
([old average rating] * [old number of votes] + [current vote]) / [new number of votes] ((3.3 * 5 + 3) / 6 = 3.25)

However there is also a drawback to storing the votes this way - you don't get to see how individual users voted. If the requirement states you need to see how individual users voted, combine approach a) and b) and you're good to go.

Upvotes: 1

Karthik
Karthik

Reputation: 1488

<?php

echo round((3+4+5+3)/4); 


or
$user1=3;
$user2=4;
$user3=5;
$user4=3

echo $count = ($user1 + $user2 + $user3 + $user4 ) / 4 

op-->4
?>

Try this it 's work perfectly ..

Upvotes: 0

Dan Puzey
Dan Puzey

Reputation: 34200

You're running into operator precedence. The division will be calculated before the addition, so you're getting this (with added brackets for clarity):

3 + 4 + 5 + (3 / 4)

... which is then rounded to 13.

Try this instead:

$count = ($user1 + $user2 + $user3 + $user4 ) / 4 

Upvotes: 4

Crast
Crast

Reputation: 49

You have to group your additions before the division.

echo round((3+4+5+3)/4);

Upvotes: 0

goto-bus-stop
goto-bus-stop

Reputation: 11824

Divisions have precedence over additions. Instead of what you do, use

echo round((3+4+5+3)/4); 

Upvotes: 2

Andreas Wong
Andreas Wong

Reputation: 60516

In math division precedes addition, so you should rewrite your equation as (3 + 4 + 5 + 3) / 4

Upvotes: 8

Related Questions