How To Avoid Division By Zero Error In Php

While working with mathematical operations in PHP, you might come across a common error called “Division by Zero”.
This error occurs when you try to divide a number by zero, which is mathematically not allowed.
For example, the following code will generate a division by zero error:


To avoid this error, all you need to do is to check whether the denominator is zero before performing the division operation.
Here’s how you can do that:


With the above code, you will no longer encounter a division by zero error, as the code checks if the $denominator is zero before performing the division.
If the denominator is zero, it will display a message saying “Cannot divide by zero.” instead of generating an error.

Another way to handle this error is by using a try-catch block with the DivisionByZeroError exception. Here’s an example:


In this method, the code is wrapped in a try block, and if a DivisionByZeroError occurs, it will be caught by the catch block.
This allows you to display your custom error message and continue with the execution of the remaining script without any interruption.

By following either of the above methods, you’ll be able to avoid division by zero error in PHP and ensure smooth execution of your code.