Code Inspection: 'foreach' variable overwrites already defined variable
Configure inspections: Settings | Editor | Inspections
Show intention actions: AltEnter
Reports the keys and values in foreach
loops that are assigned a non-primitive value before the foreach
loop and are accessed after it. Such usages may unwillingly overwrite an already defined value and cause latent bugs.
In the following example, the $value
variable is initially assigned the result of calling foo()
. When iterating over the myArr
array, the value of the current element is assigned to and overwrites $value
on each iteration. To avoid potential bugs, a new $val
variable is used inside the foreach
loop.
Suboptimal code
$value = foo();foreach ($myArr as $key => $value) {}echo $value;
Optimized code
$value = foo();foreach ($myArr as $key => $val) {}echo $value;
Place the caret at the highlighted line and press AltEnter or click
.
Click the arrow next to the inspection you want to suppress and select the necessary suppress action.