Error Identifier: unaryMinus.nonNumeric
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.
This error is reported by phpstan/phpstan-strict-rules.
Code example #
<?php declare(strict_types = 1);
function doFoo(?int $value): void
{
$result = -$value;
}
Why is it reported? #
The unary minus operator (-) is applied to a non-numeric value. In PHP, applying unary minus to non-numeric types like null, bool, string, array, or object produces unexpected results or errors. This rule enforces that only numeric types (int, float, or their union types) are used with the unary minus operator.
In the example above, $value has type int|null, and applying - to null is not a valid numeric operation.
How to fix it #
Ensure the operand is a numeric type before applying unary minus:
<?php declare(strict_types = 1);
function doFoo(?int $value): void
{
+ if ($value === null) {
+ return;
+ }
+
$result = -$value;
}
Or change the parameter type to exclude non-numeric types:
<?php declare(strict_types = 1);
-function doFoo(?int $value): void
+function doFoo(int $value): void
{
$result = -$value;
}
How to ignore this error #
You can use the identifier unaryMinus.nonNumeric to ignore this error using a comment:
// @phpstan-ignore unaryMinus.nonNumeric
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: unaryMinus.nonNumeric
Rules that report this error #
- PHPStan\Rules\Operators\OperandInArithmeticUnaryMinusRule [1] phpstan/phpstan-strict-rules