What are the common pitfalls to avoid when concatenating strings in PHP loops?

One common pitfall to avoid when concatenating strings in PHP loops is inefficient concatenation within the loop itself. This can lead to poor performance, especially with a large number of iterations. To solve this issue, it's recommended to store the strings in an array within the loop and then use the implode function outside of the loop to concatenate them efficiently.

// Example of inefficient string concatenation within a loop
$result = '';
foreach ($array as $value) {
    $result .= $value;
}

// Improved approach using an array to store strings and implode outside the loop
$results = [];
foreach ($array as $value) {
    $results[] = $value;
}
$result = implode('', $results);