1.2.323. Dangling Array References¶
Always unset a referenced-variable used in a loop.
It is highly recommended to unset blind variables when they are set up as references after a loop. When omitting this step, the next loop that will also require this variable will deal with garbage values, and produce unexpected results.
<?php
$array = array(1,2,3,4);
foreach($array as &$a) {
$a += 1;
}
// This only unset the reference, not the value
unset($a);
// Dangling array problem
foreach($array as &$a) {
$a += 1;
}
//$array === array(3,4,5,6);
// This does nothing (apparently)
// $a is already a reference, even if it doesn't show here.
foreach($array as $a) {}
//$array === array(3,4,5,5);
?>
See also No Dangling Reference, PHP foreach pass-by-reference: Do it right, or better not at all, How does PHP ‘foreach’ actually work? and References and foreach.
1.2.323.1. Suggestions¶
Avoid using the reference altogether : sometimes, the reference is not needed.
Add unset() right after the loop, to avoid reusing the reference.
1.2.323.2. Specs¶
Short name |
Structures/DanglingArrayReferences |
Rulesets |
|
Exakat since |
0.8.4 |
PHP Version |
All |
Severity |
Major |
Time To Fix |
Instant (5 mins) |
Precision |
Very high |
Features |
loop |
ClearPHP |
|
Examples |
|
Related rule |
|
Available in |