1.2.471. Foreach Needs Reference Array

When using foreach with a reference as value, the source must be a referenced array, which is a variable (or array or property or static property).

When the array is the result of an expression, the array is not kept in memory after the foreach loop, and any change made with & are lost.

This will do nothing This will have an actual effect

<?php
    foreach(array(1,2,3) as &$value) {
        $value *= 2;
    }
?>

1.2.471.1. Suggestions

  • Use a referenced array when applying modifications inside a foreach loop

1.2.471.2. Specs

Short name

Structures/ForeachNeedReferencedSource

Rulesets

All

Exakat since

0.8.4

PHP Version

All

Severity

Minor

Time To Fix

Quick (30 mins)

Precision

Very high

Features

foreach, reference

Available in

Entreprise Edition, Exakat Cloud