Recent Posts

Showing posts with label Zero. Show all posts
Showing posts with label Zero. Show all posts

How to solve: Warning: Division by zero

The warning message 'Division by zero' is one of the most commonly asked questions among new PHP developers. This error will not cause an exception, therefore, some developers will occasionally suppress the warning by adding the error suppression operator @ before the expression. For example:
$value = @(2 / 0);
But, like with any warning, the best approach would be to track down the cause of the warning and resolve it. The cause of the warning is going to come from any instance where you attempt to divide by 0, a variable equal to 0, or a variable which has not been assigned (because NULL == 0) because the result will be 'undefined'.
To correct this warning, you should rewrite your expression to check that the value is not 0, if it is, do something else. If the value is zero you should not divide, or change the value to 1 and then divide so the division results in the equivalent of having divided only by the additional variable.
if ( $var1 == 0 ) { // check if var1 equals zero
    $var1 = 1; // var1 equaled zero so change var1 to equal one instead
    $var3 = ($var2 / $var1); // divide var1/var2 ie. 1/1
} else {
    $var3 = ($var2 / $var1); // if var1 does not equal zero, divide
}