Skip to content

AlterInForeach ​

warning on by default

Group: Performance · PhpStorm name: AlterInForeachInspection

Three related foreach value-variable pitfalls:

  1. a by-reference value (as &$v) that stays alive after the loop, so a later write to $v silently modifies the last array element;
  2. an unset($v) right after a loop whose $v was not a reference (the unset is pointless, probably a leftover);
  3. (opt-in) writing back through $array[$key] = … inside foreach ($array as $key => $value) where a by-reference value would do.

Example ​

php
<?php
function adjust(array $prices, array $tags) {
    foreach ($prices as $sku => $amount) {
        $prices[$sku] = $amount * 2;
    }
    unset($sku, $amount);

    foreach ($tags as &$tag) {
        foreach ($prices as $p) {
            echo $tag, $p;
        }
    }
    unset($p);

    foreach ($tags as &$t) { $t = trim($t); }
    /** trimmed */
    unset($t);

    if ($tags) {
        foreach ($tags as & $u) { $u .= '!'; }
    }
    return $tags;
}

function tail(array $list) {
    foreach ($list as &$entry) { $entry++; }
}

Reported:

  • line 4: Iterate '$amount' by reference and assign to it directly instead of writing through the key.
  • line 6: '$amount' is not a reference here; unsetting it is unnecessary.
  • line 8: Unset '$tag' right after the loop: it is still a reference to the last element.
  • line 13: '$p' is not a reference here; unsetting it is unnecessary.

Options ​

OptionTypeDefaultEffect
SUGGEST_USING_VALUE_BY_REFboolfalseEnables part C (D7–D8). Parts A and B are always active.

Configure ​

In custos.json:

json
{
  "rules": {
    "AlterInForeach": {
      "enabled": false,
      "options": {
        "SUGGEST_USING_VALUE_BY_REF": false
      }
    }
  }
}

Suppress ​

Before the statement or declaration (or the first statement of the file), either of:

php
// @custos-ignore AlterInForeach

/**
 * @noinspection AlterInForeachInspection
 */

Released under the MIT License. Rule catalogue modelled on Php Inspections (EA Extended); independent clean-room implementation.