13. Looping Structures: while and do-while
Loops are used to execute a block of code repeatedly until a specified condition is met.
1. The while Loop
The while loop checks the condition before executing the code block. If the condition is initially false, the code block will never execute.
php
"; $count++; // Crucial: increment the counter to avoid infinite loop } /* Output: Current number: 1 ... Current number: 5 */ ?>Preventing Infinite Loops
Ensure that the loop condition eventually becomes false. This usually involves modifying the loop variable inside the block.
2. The do-while Loop
The do-while loop executes the code block at least once, and then checks the condition. If the condition is true, it repeats.
php
"; $i++; } while ($i <= 5); /* Output: The number is: 6 (Executed once, even though 6 is not <= 5) */ ?>When to use do-while: When you need the loop body to run at least one time, regardless of the initial condition (e.g., retrieving user input).