AlterInForeach
warning on by defaultGroup: Performance · PhpStorm name: AlterInForeachInspection
Three related foreach value-variable pitfalls:
- a by-reference value (
as &$v) that stays alive after the loop, so a later write to$vsilently modifies the last array element; - an
unset($v)right after a loop whose$vwas not a reference (the unset is pointless, probably a leftover); - (opt-in) writing back through
$array[$key] = …insideforeach ($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
| Option | Type | Default | Effect |
|---|---|---|---|
| SUGGEST_USING_VALUE_BY_REF | bool | false | Enables 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
*/