1.2.1065. Same Variable Foreach¶
A foreach which uses its own source as a blind variable is actually broken.
Actually, PHP makes a copy of the source before it starts the loop. As such, the same variable may be used for both source and blind value.
Of course, this is very confusing, to see the same variables used in very different ways.
The source will also be destroyed immediately after the blind variable has been turned into a reference.
<?php
$array = range(0, 10);
foreach($array as $array) {
print $array.PHP_EOL;
}
print_r($array); // display number from 0 to 10.
$array = range(0, 10);
foreach($array as &$array) {
print $array.PHP_EOL;
}
print_r($array); // display 10
?>
1.2.1065.1. Connex PHP features¶
1.2.1065.1.1. Suggestions¶
Name the source and variable names distinctly
1.2.1065.1.2. Specs¶
Short name |
Structures/AutoUnsetForeach |
Rulesets |
|
Exakat since |
1.0.5 |
PHP Version |
All |
Severity |
Minor |
Time To Fix |
Quick (30 mins) |
Precision |
High |
Available in |