Page 1 of 1

divide and 0

Posted: Mon Nov 21, 2005 1:16 am
by blacksnday
Im trying to create a rating system, and to tally the
current rating I am dividing total score by total number of votes.

If there is 0 votes (which in turn means 0 score)
it throws error of course, since dividing by zero doesnt make since.

How can I correct the below code so that if there is 0 it wont throw errors

Code: Select all

$rating = $tvotes / $nvote;

Posted: Mon Nov 21, 2005 1:21 am
by blacksnday
guess i could use something like

Code: Select all

if ($nvote == 0){
	}else{

Posted: Mon Nov 21, 2005 2:05 am
by m3mn0n
Yes. Use an if statement. Do not divide if there is nothing to divide by.

Posted: Mon Nov 21, 2005 3:48 am
by AKA Panama Jack
Or...

Code: Select all

$rating = $tvotes / max(1, $nvotes);
This way it will always be 1 or higher for the divisor.

The MIN and MAX commands are little used in PHP and they can be used to replace alot of IF/ELSE statements.

Posted: Mon Nov 21, 2005 4:00 am
by Jenk
That will give the vote a score equal to that of the total votes.. in other words, it'll give it 100%.

The if ($votes == 0) is a better solution.

Posted: Mon Nov 21, 2005 6:56 am
by sweatje

Code: Select all

$rating = ($nvote) ? $tvotes / $nvote : 0;

Posted: Mon Nov 21, 2005 7:56 am
by blacksnday
sweatje wrote:

Code: Select all

$rating = ($nvote) ? $tvotes / $nvote : 0;
thanks a ton! that works without needing IF statements.

I really needed solution without needing IF statements because
how it is currently being done, coding was doubled....

damn.. one day my mind will soak up classes and OOP
and all this extra coding will cease lol :P

Posted: Mon Nov 21, 2005 8:28 am
by Jenk
That is effectively and IF statement, just in a short 'version' called a ternary operator :)

Posted: Mon Nov 21, 2005 8:34 am
by sweatje
blacksnday wrote:
sweatje wrote:

Code: Select all

$rating = ($nvote) ? $tvotes / $nvote : 0;
thanks a ton! that works without needing IF statements.

I really needed solution without needing IF statements because
how it is currently being done, coding was doubled....

damn.. one day my mind will soak up classes and OOP
and all this extra coding will cease lol :P
No OOP is site there:

http://www.php.net/manual/en/language.o ... on.ternary