Error Identifier: booleanNot.exprNotBoolean
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);
$string = 'str';
if (!$string) {
// ...
}
Why is it reported? #
The negation operator ! is being applied to a non-boolean value. PHP will implicitly cast the value to a boolean using its type juggling rules before negating it. This implicit conversion can lead to unexpected behaviour, for example !0 is true, !'' is true, and !'0' is also true.
This rule is part of phpstan-strict-rules and enforces that only boolean values are used with the ! operator, making the code’s intent explicit.
In the example above, $string is of type string, not bool, so negating it relies on PHP’s loose type coercion.
How to fix it #
Use an explicit comparison instead of relying on type juggling:
<?php declare(strict_types = 1);
$string = 'str';
-if (!$string) {
+if ($string === '') {
// ...
}
Or cast the value to boolean explicitly before negating:
<?php declare(strict_types = 1);
$string = 'str';
-if (!$string) {
+if (!((bool) $string)) {
// ...
}
How to ignore this error #
You can use the identifier booleanNot.exprNotBoolean to ignore this error using a comment:
// @phpstan-ignore booleanNot.exprNotBoolean
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: booleanNot.exprNotBoolean
Rules that report this error #
- PHPStan\Rules\BooleansInConditions\BooleanInBooleanNotRule [1] phpstan/phpstan-strict-rules