How does PHP handle variable scope within loops and does it impact performance?

In PHP, variables declared within a loop have local scope, meaning they are only accessible within that loop. This can impact performance if the loop is iterating a large number of times because the variables will be redeclared each time, causing unnecessary overhead. To improve performance, you can declare the variables outside of the loop to avoid redeclaring them on each iteration.

// Declaring variables outside the loop
$sum = 0;

for ($i = 1; $i <= 1000; $i++) {
    $sum += $i;
}

echo $sum;