How can the declaration and appending of content to variables within a loop affect the final output in PHP?

When declaring variables within a loop in PHP, it's important to be mindful of scope and reinitialization. If a variable is declared inside a loop and its value is appended in each iteration, the final output may not be as expected due to reinitialization of the variable. To solve this issue, declare the variable outside the loop and append to its value within the loop.

$output = ""; // Declare the variable outside the loop

for ($i = 0; $i < 5; $i++) {
    $output .= "Iteration $i\n"; // Append content to the variable
}

echo $output; // Output the final content