You are strongly advised to check corresponding YouTube video at the end of this article.
While and do..while are loop structures in programming languages that allow a piece of code to be executed repeatedly until a certain condition is met.
The while
loop executes a block of code while a condition is true. It first evaluates the condition, and if it is true, it enters the loop and executes the block of code. Once the code is executed, it evaluates the condition again, and if it's still true, it executes the code again, repeating this process until the condition becomes false. If the condition is initially false, the block of code is not executed at all.
The do..while
loop is similar to the while
loop, but the block of code is executed at least once before the condition is evaluated. First, the block of code is executed, and then the condition is evaluated. If it is true, the loop executes again, repeating the process. If it's false, the loop terminates.
While loops are useful when we don't know in advance how many times we need to execute a block of code, and do..while loops are useful when we want to ensure that a block of code is executed at least once.
<?php
$x = 0;
while ($x < 10) {
echo "Right now: $x <br>";
$x = $x + 1;
}
/*
for ($x = 0; $x < 10; $x = $x + 1) {
echo "Right now: $x <br>";
}
*/
?>
This code is an example of a while
loop in PHP. The loop executes the code inside its block as long as the condition $x < 10
is true.
The code initializes a variable $x
to 0 before entering the loop. Inside the loop, it first prints the value of $x
using the echo
statement. Then, it increments the value of $x
by 1 using the $x = $x + 1
statement. This process repeats until the value of $x
is no longer less than 10, at which point the loop ends.
This code is functionally equivalent to the commented-out for
loop that appears at the bottom of the script.
The for
loop is another type of loop that is often used for iterating over a sequence of values. In this case, the for
loop initializes the variable $x
to 0, checks the condition $x < 10
, and increments the value of $x
by 1 with each iteration, just like the while
loop.
However, the for
loop includes all three of these steps in its header, making it a more concise way to express this type of loop.
<?php
$x = 0;
do {
echo "Right now: $x <br>";
$x = $x + 1;
} while ($x < 10);
?>
This PHP script demonstrates the use of a "do-while" loop.
The code inside the curly braces will be executed at least once, regardless of the condition specified in the while statement.
In this example, the variable $x is initialized to zero, and the loop will execute until $x is no longer less than 10. During each iteration, the value of $x is echoed to the screen along with some text. The value of $x is then incremented by 1.
The loop will continue to execute until the value of $x is 10 or greater.
No comments:
Post a Comment