Ffile2fix
Sign in Get started

How to fix "DivisionByZeroError: Division by zero" in PHP

Fatal error: Uncaught DivisionByZeroError: Division by zero in /home/user/public_html/report.php:57

The code divided a number by zero (or used % with zero), which PHP 8 treats as a fatal error. In PHP 7 the / operator only warned and returned INF or false, so old code often breaks after upgrading.

Also appears as: Uncaught DivisionByZeroError: Modulo by zero · PHP Fatal error: Uncaught DivisionByZeroError: Division by zero in wp-content/plugins/... · Warning: Division by zero (PHP 7)

Common causes

  • Calculating averages or percentages over an empty set (count() is 0)
  • A missing database value (null) or a "0" setting used as the divisor
  • Upgrading from PHP 7, where / by zero was only a warning
  • Modulo with a zero divisor, such as pagination with 0 items per page
  • A plugin calculating ratios from settings that were never saved

How to fix it

  1. Find the divisor on the reported line. Identify which variable is on the right of / or % and log its value before the operation.
  2. Guard the division. Check the divisor first: $avg = $count > 0 ? $sum / $count : 0; and choose a sensible fallback for your case.
  3. Handle empty data upstream. Return early or show 'no data' when a query or array is empty instead of running calculations on it.
  4. Validate settings and input. Ensure values like items_per_page or rates are positive integers before saving and before use.
  5. Catch it where a fallback makes sense. Wrap the calculation in try { ... } catch (DivisionByZeroError $e) { ... } when division happens deep inside a library call.
  6. Use fdiv() for float math that should return INF. fdiv($a, 0) returns INF, -INF or NAN instead of throwing, which suits scientific code but rarely business logic.

PHP 8

$count = count($orders);
$average = $count > 0 ? $total / $count : 0.0;

try {
    $ratio = intdiv($a, $b);
} catch (DivisionByZeroError $e) {
    $ratio = 0;
}

How to stop it happening again

  • Always check divisors that come from data or user input
  • Test calculations with empty datasets
  • Scan legacy code for unguarded divisions before upgrading to PHP 8

Frequently asked questions

Why did this only start after upgrading PHP?

PHP 8 changed division by zero with / from a warning to a DivisionByZeroError. Modulo by zero already threw in PHP 7.

Can I just suppress it with @?

No. It is an Error exception, not a warning, so @ does not stop it. Guard the divisor or catch DivisionByZeroError.

Does 0.0 also trigger it?

Yes. Dividing by 0, 0.0, null or the string "0" throws DivisionByZeroError. A non-numeric string such as "" or "abc" throws a TypeError (Unsupported operand types) instead.