1.2.27. Altering Foreach Without Reference

Foreach() loop that could use a reference as value.

When using a foreach loop that modifies the original source, it is recommended to use referenced variables, rather than access the original value with $source[$index].

Using references is then must faster, and easier to read.

array_walk() and array_map() are also alternative to prevent the use of foreach(), when $key is not used.

<?php

// Using references in foreach
foreach($source as $key => &$value) {
    $value = newValue($value, $key);
}

// Avoid foreach : use array_map
$source = array_walk($source, 'newValue');
    // Here, $key MUST be the second argument or newValue

// Slow version to update the array
foreach($source as $key => &$value) {
    $source[$key] = newValue($value, $key);
}
?>

See also foreach.

1.2.27.1. Suggestions

  • Add the reference on the modified blind variable, and avoid accessing the source array

1.2.27.2. Specs

Short name

Structures/AlteringForeachWithoutReference

Rulesets

All, Analyze, CE, CI-checks

Exakat since

0.8.4

PHP Version

All

Severity

Major

Time To Fix

Quick (30 mins)

Precision

High

Features

foreach, loop

ClearPHP

use-reference-to-alter-in-foreach

Examples

Contao, WordPress

Related rule

Dangling Array References

Available in

Entreprise Edition, Community Edition, Exakat Cloud