need help with division by zero error handling

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Obadiah
Forum Regular
Posts: 580
Joined: Mon Jul 31, 2006 9:13 am
Location: Ashland, KY
Contact:

need help with division by zero error handling

Post by Obadiah »

Im trying to do a bit of error handling with averages because as of now im getting a
Warning: division by zero
So what I tried is this

Code: Select all

if ($sumAll_nums = 0 ){
	$Avg_nums = "-";
}
else if ($numOf_nums = 0){
	$Avg_nums = "-";
}
else if (($sumAll_nums != 0 )&&($numOf_nums != 0)){
	$Avg_nums = $sumAll_nums / $numOf_nums;
}

echo "average" .$Avg_nums;
and this

Code: Select all

if (($sumAll_nums = 0 ) || ($numOf_nums = 0)){
	$Avg_nums = "-";
}
else if (($sumAll_nums != 0 ) && ($numOf_nums != 0)){
	$Avg_nums = $sumAll_nums / $numOf_nums;
}

echo "average" .$Avg_nums;
it prints out nothig....no zero no "-" nothing... what am I doing wrong here?
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: need help with division by zero error handling

Post by Celauran »

You're using assignment operators in your if statements.

Fixed:

Code: Select all

if ($sumAll_nums == 0 ){
        $Avg_nums = "-";
}
else if ($numOf_nums == 0){
        $Avg_nums = "-";
}
else if (($sumAll_nums != 0 )&&($numOf_nums != 0)){
        $Avg_nums = $sumAll_nums / $numOf_nums;
}

echo "average" .$Avg_nums;
Post Reply