Error Identifier: while.condNotBoolean
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);
$someString = 'hello';
while ($someString) {
$someString = '';
}
Why is it reported? #
This error is reported by phpstan-strict-rules.
The condition of the while loop is not a boolean value. PHP will implicitly convert the value to a boolean using its loose truthiness rules, which can lead to unexpected behavior. For example, 0, '', '0', [], and null are all falsy, while other values of the same types are truthy. Relying on implicit type coercion in conditions makes the code harder to reason about.
How to fix it #
Use an explicit boolean comparison:
$someString = 'hello';
-while ($someString) {
+while ($someString !== '') {
$someString = '';
}
Or cast to boolean explicitly to make the intent clear:
$someString = 'hello';
-while ($someString) {
+while ((bool) $someString) {
$someString = '';
}
How to ignore this error #
You can use the identifier while.condNotBoolean to ignore this error using a comment:
// @phpstan-ignore while.condNotBoolean
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: while.condNotBoolean
Rules that report this error #
- PHPStan\Rules\BooleansInConditions\BooleanInWhileConditionRule [1] phpstan/phpstan-strict-rules