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);
/** @param positive-int $i */
function doFoo(int $i): void
{
if ($i != 0) {
echo 'always nonzero';
}
}
Why is it reported? #
The loose comparison using != always evaluates to true based on the types PHPStan has inferred. This means the condition is always satisfied, making it redundant, and any else branch would be dead code.
The != operator performs a loose (type-juggling) comparison. PHPStan reports this when it can determine from the types that the two values can never be loosely equal, regardless of the actual runtime values.
In the example above, $i is a positive-int (always >= 1), so $i != 0 is always true.
How to fix it #
Remove the redundant condition:
/** @param positive-int $i */
function doFoo(int $i): void
{
- if ($i != 0) {
- echo 'always nonzero';
- }
+ echo 'always nonzero';
}
Or fix the comparison value so the condition becomes meaningful:
/** @param positive-int $i */
function doFoo(int $i): void
{
- if ($i != 0) {
+ if ($i != 1) {
echo 'not one';
}
}
Consider using strict comparison (!==) instead of loose comparison, which avoids type-juggling surprises:
/** @param positive-int $i */
function doFoo(int $i): void
{
- if ($i != 0) {
+ if ($i !== 1) {
// ...
}
}
How to ignore this error #
You can use the identifier notEqual.alwaysTrue to ignore this error using a comment:
// @phpstan-ignore notEqual.alwaysTrue
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: notEqual.alwaysTrue
Rules that report this error #
- PHPStan\Rules\Comparison\ConstantLooseComparisonRule [1]