What common mistakes can lead to an infinite loop in a for loop in PHP, and how can they be prevented?
Common mistakes that can lead to an infinite loop in a for loop in PHP include not updating the loop control variable properly within the loop, using the wrong comparison operator in the loop condition, or not having a proper exit condition. To prevent this, always ensure that the loop control variable is updated correctly, use the correct comparison operator in the loop condition, and have a clear exit condition to break out of the loop when needed.
// Incorrect loop that can lead to an infinite loop
for ($i = 0; $i <= 10; $i) {
echo $i;
}
// Corrected loop with proper update of loop control variable
for ($i = 0; $i <= 10; $i++) {
echo $i;
}