Error Identifier: ternary.alwaysFalse
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(): void
{
$zero = 0;
$result = $zero ? 'yes' : 'no';
}
Why is it reported? #
The condition of the ternary operator always evaluates to false, which means the “true” branch can never be reached. This typically indicates a logic error, dead code, or a condition that does not express the intended check.
In the example above, $zero is assigned 0, which is always falsy in PHP, so the ternary will always evaluate to 'no'.
How to fix it #
Fix the condition so it can actually evaluate to both true and false:
<?php declare(strict_types = 1);
-function doFoo(): void
+function doFoo(int $value): void
{
- $zero = 0;
- $result = $zero ? 'yes' : 'no';
+ $result = $value > 0 ? 'yes' : 'no';
}
Or if the condition is intentionally always false, simplify the code by using the false-branch value directly:
<?php declare(strict_types = 1);
function doFoo(): void
{
- $zero = 0;
- $result = $zero ? 'yes' : 'no';
+ $result = 'no';
}
How to ignore this error #
You can use the identifier ternary.alwaysFalse to ignore this error using a comment:
// @phpstan-ignore ternary.alwaysFalse
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: ternary.alwaysFalse
Rules that report this error #
- PHPStan\Rules\Comparison\TernaryOperatorConstantConditionRule [1]