A division-by-zero error will occur in PHP if:
- The variable you’re dividing by (the divisor) has been set to zero.
- The divisor has been set to null.
- The variable does not exist. i.e., it has not been created yet.
The following example code will reproduce the error:
$var = 0;
echo 12 / $var;
If you run the code above, you will experience a “Warning: Division by zero” warning. In newer versions of PHP, the script will throw a fatal DivisionByZeroError exception.
This is because the $var variable has been set to 0.
Performing a basic check can prevent this issue. For example, you can wrap your division arithmetic inside an IF statement:
$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.
It is worth noting that older versions of PHP will continue to execute if a division error is encountered. This may lead to incorrect calculations.
However, newer versions of PHP will throw a DivisionByZeroError exception.