Error Identifier: mod.rightNonNumeric
Every error reported by PHPStan has an error identifier. Here’s a list of all error identifiers. In PHPStan Pro you can see the error identifier next to each error and filter errors by their identifiers.
Code example #
<?php declare(strict_types = 1);
function doFoo(int $a, ?string $b): void
{
$result = $a % $b;
}
Why is it reported? #
This error is reported by phpstan/phpstan-strict-rules.
The right-hand side operand of a modulo (%) is not a numeric type. PHP’s modulo operator expects both operands to be numeric (int, float, or numeric-string). Using a non-numeric type such as null, array, object, or a non-numeric string on the right side of a modulo operation will produce unexpected results or a TypeError in strict mode. A null right operand is equivalent to zero, which causes a DivisionByZeroError.
How to fix it #
Ensure the right-hand operand is a numeric type by narrowing the type:
<?php declare(strict_types = 1);
-function doFoo(int $a, ?string $b): void
+function doFoo(int $a, int $b): void
{
$result = $a % $b;
}
Or validate and convert the value before use:
<?php declare(strict_types = 1);
function doFoo(int $a, ?string $b): void
{
- $result = $a % $b;
+ if ($b !== null && is_numeric($b)) {
+ $result = $a % (int) $b;
+ }
}
How to ignore this error #
You can use the identifier mod.rightNonNumeric to ignore this error using a comment:
// @phpstan-ignore mod.rightNonNumeric
codeThatProducesTheError();
You can also use only the identifier key to ignore all errors of the same type in your configuration file in the ignoreErrors parameter:
parameters:
ignoreErrors:
-
identifier: mod.rightNonNumeric
Rules that report this error #
- PHPStan\Rules\Operators\OperandsInArithmeticModuloRule [1] phpstan/phpstan-strict-rules