1.2.375. Don’t Reuse Foreach Source¶
It is dangerous to reuse the same variable inside a loop that use it as a source.
PHP actually takes a copy of the source, so the foreach() loop is not affected by the modification.
On the other hand, the source of the loop is modified after the loop (and actually, also during), which may come as a surprise to a later coder.
<?php
$properties = [];
foreach ($values as $i => $vars) {
// $values is used again here, now as a blind variable
foreach ($vars as $class => $values) {
foreach ($values as $name => $v) {
$properties[$class][$name][$i] = $v;
}
}
}
?>
1.2.375.1. Connex PHP features¶
1.2.375.1.1. Suggestions¶
Do not reuse the source as another variable
Use different names to disambiguate their purpose
1.2.375.1.2. Specs¶
Short name |
Structures/DontReuseForeachSource |
Rulesets |
|
Exakat since |
2.3.5 |
PHP Version |
All |
Severity |
Minor |
Time To Fix |
Quick (30 mins) |
Precision |
Very high |
Available in |