String Concat In Loop
ID |
php.string_concat_in_loop |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Efficiency |
Language |
Php |
Tags |
efficiency, loop |
Description
Reports repeated string concatenation that accumulates into the same variable inside a loop,
either with the .= operator ($out .= $part;) or the plain $out = $out . $part; form.
Rationale
PHP strings are immutable, so every concatenation allocates a new string and copies the whole
accumulated content into it. Doing this once per iteration makes the cost grow with the square
of the number of iterations. Collecting the pieces in an array and joining them once with
implode() after the loop runs in linear time and is usually clearer as well.
<?php
$out = '';
foreach ($parts as $part) {
$out .= $part; // FLAW — quadratic concatenation in the loop
}
$pieces = [];
foreach ($parts as $part) {
$pieces[] = $part; // OK — collect the parts
}
$out = implode('', $pieces); // OK — join once after the loop
Remediation
Append the pieces to an array inside the loop and call implode() once after it. Augmented
arithmetic such as $total += $n is unaffected — only string concatenation (.= or
$x = $x . …) is reported.