1.2.895. Overwritten Foreach Var

When using standard blind variable names, nested foreach may lead to overwriting the variables.

Careful coding may take advantage of that feature. Though, it tends to be error prone, and will generate bugs if the code is refactored.

<?php

foreach($array as $key => $value) {
    foreach($array as $key2 => $value) {
        // $value is now the one of the 2nd foreach, not the first.

    }
}

?>

1.2.895.1. Suggestions

  • Change the name of one of the blind variable to use a distinct name

  • Remove usage of one of the double variable

  • Remove the nested foreach()

  • Move the nested foreach() to a method

1.2.895.2. Specs

Short name

Structures/OverwrittenForeachVar

Rulesets

All, Analyze

Exakat since

2.3.2

PHP Version

All

Severity

Major

Time To Fix

Quick (30 mins)

Precision

Very high

Features

foreach

Available in

Entreprise Edition, Exakat Cloud