1.2.127. Check Division By Zero

Always check before dividing by a value. If that value is cast to 0, PHP might stop the processing with an exception, or keep processing it with 0 as a result. Both will raise problems.

The best practise is to check the incoming value before attempting the division. On possible alternative is to catch the DivisionByZeroError <https://www.php.net/manual/en/class.`divisionbyzeroerror.php>`_ exception, that PHP 8.0 and more recent will raise.

<?php

// Check the value before usage
function foo($a = 1) {
    if ($a !== 0) {
        return 42 / $a;
    } else {
        // process an error
    }
}

// Check the value after usage (worse than the above)
function foo($a = 1) {
    try {
        return 42 / $a;
    } catch (DivisionByZero) {
        // fix the situation now
    }
}

// This might fails with a division by 0
function foo($a = 1) {
    return 42 / $a;
}

?>

See also DivisionByZeroError.

1.2.127.1. Specs

Short name

Structures/CheckDivision

Rulesets

All, Analyze, Changed Behavior

Exakat since

2.3.3

PHP Version

All

Severity

Minor

Time To Fix

Quick (30 mins)

Precision

High

Features

exception, arithmeticerror

Related rule

Could Use Try

Available in

Entreprise Edition, Exakat Cloud