1.2.1166. Strict Comparison With Booleans¶
Strict comparisons prevent mistaking an error with a false.
Boolean values may be easily mistaken with other values, especially when the function may return integer or boolean as a normal course of action.
It is encouraged to use strict comparison === or !== when booleans are involved in a comparison. switch() structures always uses == comparisons. Since PHP 8.0, it is possible to use match() to have strict comparisons. This is not reported by this analysis, as every switch should be refactored.
Native functions in_array(), array_keys() and array_search() have a third parameter to make it use strict comparisons.
<?php
// distinguish between : $b isn't in $a, and, $b is at the beginning of $a
if (strpos($a, $b) === 0) {
doSomething();
}
// DOES NOT distinguish between : $b isn't in $a, and, $b is at the beginning of $a
if (strpos($a, $b)) {
doSomething();
}
// will NOT mistake 1 and true
$a = array(0, 1, 2, true);
if (in_array($a, true, true)) {
doSomething();
}
// will mistake 1 and true
$a = array(0, 1, 2, true);
if (in_array($a, true)) {
doSomething();
}
?>
1.2.1166.1. Connex PHP features¶
1.2.1166.1.1. Suggestions¶
Use strict comparison whenever possible
1.2.1166.1.2. Specs¶
Short name |
Structures/BooleanStrictComparison |
Rulesets |
|
Exakat since |
0.8.4 |
PHP Version |
All |
Severity |
Minor |
Time To Fix |
Quick (30 mins) |
Precision |
High |
Examples |
|
Available in |