Division by zero error

Seth-77 picture Seth-77 · Oct 18, 2013 · Viewed 24.9k times · Source

I have this code throwing up the error:

<?php

    $val1 = $totalsum;
    $res = ( $val1 / $val2) * 100;
    $val2 = count($allcontent);
    $res = ( $val1 / $val2) * 100;
    // 1 digit after the decimal point
    $res = round($res, 1); // 66.7

    echo "Success: ";
    echo $res;
    echo "%";

?>

I have tried adding this line:

if ($res === 0) 
{ 
   echo "not eligible"; 
}

but it still gives the error. any ideas?

Answer

Chris Rasco picture Chris Rasco · Oct 18, 2013

You'd want to check $val2 before the division occurs:

<?php
$val1 = $totalsum;
$val2 = count($allcontent);
if($val2 != 0)
{
    $res = ( $val1 / $val2) * 100;
    // 1 digit after the decimal point
    $res = round($res, 1); // 66.7
    echo "Success: ".$res."%";
}
else
{
    echo "Count of allcount was 0";
}
?>