Boolean Compare With Literal
ID |
php.boolean_compare_with_literal |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Code Smell |
Language |
Php |
Tags |
code_smell, suspicious-comparison |
Description
Reports a strict comparison (=== or !==) in which one operand is the boolean literal
true or false, such as $flag === true or $done !== false. These comparisons add no
information and read worse than testing the boolean directly.
Rationale
When the operand is already a boolean, comparing it to a literal is redundant: $flag === true
is equivalent to $flag, and $flag !== false is also equivalent to $flag. Dropping the
literal makes the condition shorter and clearer, and removes a common copy-paste source of
inverted logic (=== false vs !== false).
This rule covers only the strict operators. Loose comparisons against a boolean literal
($x == true, $x != false) are reported by the strict-comparison rule, so scoping this rule
to ===/!== keeps the two from flagging the same line twice.
<?php
if ($flag === true) { // FLAW - redundant, write if ($flag)
run();
}
if ($flag !== false) { // FLAW - redundant, write if ($flag)
run();
}
if ($flag) { // OK - direct boolean test
run();
}
Remediation
Test the boolean directly. Replace $x === true and $x !== false with $x, and replace
$x === false and $x !== true with !$x.