While Loop
Let's get acquainted with the while loop and its basic syntax in this lesson.
We'll cover the following
What is a while
loop?
The while
loop consists of a condition. If the condition is true, then the body of the loop is executed and the condition is checked again. This process is repeated until the condition becomes false. The syntax is as follows:
The curly braces surrounding the body of the while
loop indicate that multiple statements can be executed as part of this loop.
Example
Here’s a look at the while
loop code:
$x=4;$y=0;while ( $y <= 10 ) { # the while loop will run till y<=10 condition is being met$y += $x;$x += 1;} #the loop will iterate 3 timesprint "the value of x is: $x\n";print "the value of y is: $y\n";
Explanation
Below is an illustration of the code above to help us better understand this logic.
If the variable(s) involved in the while loop condition do not change while it executes, then the loop condition would either always be true, or always be false. If the loop condition is always true, this creates an infinite loop. This is demonstrated in the following example:
$y = 0;$x = 4;while ( $y <= 10 ) { #since y is not being changed inside the while loop you will get stuck$x += 1; # in an infinite loop as the condition will always be met}$y += $x;
According to what is written, even though the second line after the while
was incremented, only the first line corresponds to the while
loop. This is a huge problem, because the variable involved in the condition ($y <= 10)
, i.e. $y
, does not change, so it will always evaluate to “true”, making this an infinite loop. We can follow the above example and its advice to always make sure that we don’t have an infinite loop.