6

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?

Seth-77
  • 254
  • 2
  • 4
  • 15

5 Answers5

16

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";
}
?>
Chris Rasco
  • 2,713
  • 1
  • 18
  • 22
2

You have the following in your code:

$val2 = count($allcontent);

If the $allcontent array is empty, then the value of $val2 will be 0, and you will essentially be doing:

$res = ( $val1 / 0) * 100;

As expected, this will cause PHP to return the 'Division by zero' error.

To make sure this doesn't happen, simply use an if statement:

if ($val2 != 0) {
    $res = ( $val1 / $val2) * 100;
    // 1 digit after the decimal point
    $res = round($res, 1); // 66.7
    echo "Success: ";
    echo $res;
    echo "%";
}

This can be rewritten using sprintf():

if ($val2 > 0) {
    $res = round( ($val1 / $val2) * 100 , 1); // 66.7
    echo sprintf('Success: %d%%', $res); // % is used for escaping the %
}

It does the same thing, but looks a bit more cleaner, in my opinion.

Amal Murali
  • 75,622
  • 18
  • 128
  • 150
1
if($val2!=0){
  //Do it
}else{
  //Don't
}
undone
  • 7,857
  • 4
  • 44
  • 69
0

Make sure $val2 is NOT zero before trying to divide $val1 with it. Try this:

<?php
    $val1 = $totalsum;
    $res = ( $val1 / $val2) * 100;
    $val2 = count($allcontent);

    if( $val2 != 0 ){
        $res = ( $val1 / $val2) * 100;
        // 1 digit after the decimal point
        $res = round($res, 1); // 66.7
        echo "Success: ";
        echo $res;
        echo "%";
    }
?>
Zest
  • 1
  • 3
  • Welcome to Stack Overflow! Although this code may help to solve the problem, it doesn't explain _why_ and/or _how_ it answers the question. Providing this additional context would significantly improve its long-term educational value. Please [edit] your answer to add explanation, including what limitations and assumptions apply. – Toby Speight Oct 04 '16 at 13:18
-2

I'm guessing $val2 is coming out to 0. Make sure $allcontent is being initialized and filled.

felipsmartins
  • 13,269
  • 4
  • 48
  • 56
Jack B
  • 139
  • 7