PHP – Warning: Division by zero

A division by zero error can occur in PHP whenever:

  • The variable you’re dividing with has been set to zero (this number is called the divisor).
  • The variable you’re dividing with has been set to null.
  • The variable does not exist. i.e. It has not been set.

Example code that will reproduce the error:

$var = 0;
echo 12 / $var;

If you run the code above, you’ll be faced with the following error: Warning: Division by zero. This is because our variable $var has been set to 0.

Fortunately, this common warning can be avoided by carrying out some very basic checking. To avoid this type of error, you can wrap your division arithmetic inside an IF statement, like so:

$var = 0;
if($var > 0){
    echo 12 / $var;

The code above is pretty simple. Basically, we make sure that the variable (in this case, our divisor) is greater than 0 before we attempt our division calculation.

PS: It is important to note that this will not prevent your script from executing. In other languages, division by zero can lead to an exception that essentially kills the program.