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
- Find the divisor on the reported line. Identify which variable is on the right of / or % and log its value before the operation.
- Guard the division. Check the divisor first: $avg = $count > 0 ? $sum / $count : 0; and choose a sensible fallback for your case.
- Handle empty data upstream. Return early or show 'no data' when a query or array is empty instead of running calculations on it.
- Validate settings and input. Ensure values like items_per_page or rates are positive integers before saving and before use.
- Catch it where a fallback makes sense. Wrap the calculation in try { ... } catch (DivisionByZeroError $e) { ... } when division happens deep inside a library call.
- 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