Do-While Loop with Arrays:
This loop executes a block of code at least once, then continues to loop as long as a condition remains true. It’s particularly useful for processing arrays where you need to guarantee at least one iteration.
Structure:
PHP Code
do {
// Code to be executed (processes array elements)
$condition; // Update condition variable
} while ($condition);
Example:
PHP Code
$fruits = [“apple”, “banana”, “orange”];
$i = 0;
do {
echo $fruits[$i] . ” “;
$i++;
} while ($i < count($fruits)); // Loop until all elements processed
Use code with caution.
content_copy
Key Points:
- The code within the do block executes at least once.
- The while condition determines if the loop continues.
- Update the condition variable within the loop.
This do-while loop iterates through the fruits array, printing each element and incrementing the counter ($i) until all elements are processed.
Here’s another example of Do-While Loop.