1.2.538. Identical Variables In Foreach

Do not use the same variable names as a foreach() source and one of its blind variables.

Foreach() makes a copy of the original data while working on it : this prevents any interference. Yet, when the source and the blind variable is the same, the source will have changed after the loop.

<?php

// classic way to use a foreach loop
foreach($array as $key => $value) {
    // doSomething with $key and $value
}

// unusual way to end up with a name conflict
foreach($a as $a => [$b, $c, $a]) {
    // doSomething with $a and $a, $b, $c
}


// classic way to use a foreach loop
foreach($a as $a => $b) {
    // doSomething with $a and $a
}
// Now, after the loop, $a is an integer or a string!

?>

1.2.538.1. Suggestions

  • Use a different name for the source of the array and the blind values

1.2.538.2. Specs

Short name

Structures/IdenticalVariablesInForeach

Rulesets

All, Analyze

Exakat since

2.3.9

PHP Version

All

Severity

Minor

Time To Fix

Quick (30 mins)

Precision

Very high

Features

foreach

Available in

Entreprise Edition, Exakat Cloud