Discovering While and Do-While Loops
Discover Loops with While and Do-While
Welcome to the exciting world of loops in PHP! In this lesson, we will explore two types of loops: the while loop and the do-while loop. Loops are a fundamental concept in programming as they allow us to repeat a set of instructions until a specific condition is met. By using loops, we eliminate the need to write redundant code, making our scripts more concise and easier to maintain.
What You'll Learn
In this unit, we will break down the while loop and do-while loop, showing you how they work and providing practical examples to implement them. By the end of this lesson, you'll be able to write scripts that can count down for a spaceship launch, which is a perfect example of when and why to use these loops.
While Loop
The while loop repeats a block of code as long as the specified condition is true. In the example below, the loop will continue to execute as long as the $countdown variable is greater than 0. After each iteration, the $countdown variable is decremented by 1.
Upon running the above code, you will see the following countdown sequence:
Do-While Loop
The do-while loop is similar to the while loop, but with one key difference: it guarantees that the block of code will execute at least once. This is because the condition is checked after the code has executed. In the example below, the loop will execute and decrement the $countdown variable by 1 until it is no longer greater than 0.
Executing the above snippet will result in the following output:
