What are the best practices for handling and avoiding variable reassignment within loops in PHP?

Variable reassignment within loops can lead to unexpected behavior and errors in PHP. To avoid this, it is best practice to use a different variable for the loop iteration instead of reassigning the same variable. This helps to maintain clarity and prevent unintended side effects in the code.

// Avoiding variable reassignment within loops in PHP

// Incorrect way
$numbers = [1, 2, 3, 4, 5];
$total = 0;

foreach ($numbers as $number) {
    $total += $number;
}

echo $total; // Output: 15

// Correct way
$numbers = [1, 2, 3, 4, 5];
$total = 0;

foreach ($numbers as $num) {
    $total += $num;
}

echo $total; // Output: 15