1.2.786. No Append On Source

Do not append new elements to an array in a foreach loop. Since PHP 7.0, the array is still used as a source, and will be augmented, and used again.

Thanks to Frederic Bouchery for the reminder.

<?php

// Relying on the initial copy
$a = [1];
$initial = $a;
foreach($initial as $v) {
    $a[] = $v + 1;
}

// Keep new results aside
$a = [1];
$tmp = [];
foreach($a as $v) {
    $tmp[] = $v + 1;
}
$a = array_merge($a, $tmp);
unset($tmp);

// Example, courtesy of Frederic Bouchery
// This is an infinite loop
$a = [1];
foreach($a as $v) {
    $a[] = $v + 1;
}

?>

See also foreach and What will this code return? #PHP.

1.2.786.1. Suggestions

  • Use a copy of the source, to avoid modifying it during the loop

  • Store the new values in a separate storage

1.2.786.2. Specs

Short name

Structures/NoAppendOnSource

Rulesets

All, Analyze

Exakat since

1.8.2

PHP Version

All

Severity

Minor

Time To Fix

Quick (30 mins)

Precision

Very high

Features

class

Available in

Entreprise Edition, Exakat Cloud