I'm new to PHP and I have an error on my website and can't figure out the right way to fix it.
The error:
Warning: Division by zero
The code I'm using:
public function percent($num_amount, $num_total)
{
$count1 = $num_amount / $num_total;
$count2 = $count1 * 100;
$count = round($count2);
return $count;
}
I know it has something to do with dividing by 0 which obviously can't. But how do I change that and fix this error?
Simply....
public function percent($num_amount, $num_total)
{
if($num_total > 0){
$count1 = $num_amount / $num_total;
$count2 = $count1 * 100;
$count = round($count2);
return $count;
}else{
return 0; // or whatever you want
}
}
If $num_total
is zero, then check if $num_amount
is also zero. If it is, then return a value that's appropriate (possibly 100%). If $num_amount
is not also zero then you have some logic error which you should flag.