1.2.53. Assign And Compare¶
Assignation has a lower precedence than comparison. As such, the assignation always happens after the comparison. This leads to the comparison being stored in the variable, and not the value being compared.
<?php
if ($id = strpos($string, $needle) !== false) {
// $id now contains a boolean (true or false), but not the position of the $needle.
}
// probably valid comparison, as $found will end up being a boolean
if ($found = strpos($string, $needle) === false) {
doSomething();
}
// always valid comparison, with parenthesis
if (($id = strpos($string, $needle)) !== false) {
// $id now contains a boolean (true or false), but not the position of the $needle.
}
// Being a lone instruction, this is always valid : there is no double usage with if condition
$isFound = strpos($string, $needle) !== false;
?>
See also Operator Precedence.
1.2.53.1. Connex PHP features¶
1.2.53.1.1. Suggestions¶
Use parenthesis
Separate assignation and comparison
Drop assignation or comparison
1.2.53.1.2. Specs¶
Short name |
Structures/AssigneAndCompare |
Rulesets |
|
Exakat since |
1.6.3 |
PHP Version |
All |
Severity |
Minor |
Time To Fix |
Quick (30 mins) |
Precision |
High |
Available in |