Why This Happens
PHP raises this warning when you attempt to divide by zero using the / or % operators. In PHP 8+, dividing an integer by zero throws a DivisionByZeroError. This commonly occurs with user-supplied values, empty arrays used in average calculations, or counters that were never incremented.
The Problem
function average(array $numbers): float {
return array_sum($numbers) / count($numbers);
}
echo average([]); // Division by zeroThe Fix
function average(array $numbers): float {
$count = count($numbers);
if ($count === 0) {
return 0.0;
}
return array_sum($numbers) / $count;
}Step-by-Step Fix
- 1
Find the division operation
Locate the / or % operator on the line mentioned in the error message.
- 2
Identify why the divisor is zero
Check if the divisor comes from user input, a count of an empty collection, or a variable that was not properly initialized.
- 3
Add a zero check
Add a conditional check to handle the zero case before the division, returning a default value or throwing a descriptive exception.
Bugsly catches this automatically
Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.
Try Bugsly free