What are the potential pitfalls of trying to identify the last iteration of a loop in PHP and how can they be avoided?

When trying to identify the last iteration of a loop in PHP, a common pitfall is incorrectly determining the last iteration due to off-by-one errors or incorrect loop conditions. To avoid this, you can use a counter variable to track the current iteration and compare it to the total number of iterations.

// Example loop with counter variable to identify last iteration
$totalIterations = 5;
$counter = 1;

while ($counter <= $totalIterations) {
    if ($counter == $totalIterations) {
        echo "This is the last iteration.";
    } else {
        echo "Iteration $counter";
    }
    
    $counter++;
}