While Loops in PHP
Looping the Loop(1/7)
A loop is a structure that tells a computer to execute a set of statements multiple times. If you have a process that you want repeated hundreds of times, it pays to put it in a loop so you don't need to write hundreds of lines of code.
If you are working on these courses in order, you have already seen how a for loop can allow for a set number of loop iterations. But what about a situation where (due to randomness, perhaps) you don't know how many times the loop should repeat? In that case, you can use a while loop.
A while loop will execute as long as a certain condition is true. For example, the loop in the editor will simulate coin flips as long as the number of consecutive heads is less than 3.
Instructions
Take a look at the code in the editor and see if you understand how it will work. Once you think you know (or if you're stumped, no pressure!) click Save & Submit Code and see what happens. Check the hint if you would like an explanation.
Hint
Before the loop, variables are defined to count the number of consecutive heads, $headCount, and the total number of flips, $flipCount.
The loop executes as long as $headCount is less than 3. Inside the loop rand(0,1) randomly outputs either a 0 or 1 representing tails and heads respectively, and $flipCount increases by one. If the result is heads (1 evaluates as true) $headCount increases by one and the heads <div> is echoed to the page. If not, $headCount becomes 0 and the tails <div> is echoed to the page.
When the loop is done, $flipCount is echoed to the page within a paragraph.
index.php
<!DOCTYPE html>
<html>
<head>
<link type='text/css' rel='stylesheet' href='style.css'/>
<title>Coin Flips</title>
</head>
<body>
<p>We are going to flip a coin until we get three heads in a row!</p>
<?php
$headCount = 0;
$flipCount = 0;
while ($headCount < 3) {
$flip = rand(0,1);
$flipCount ++;
if ($flip){
$headCount ++;
echo "<div class=\"coin\">H</div>";
}
else {
$headCount = 0;
echo "<div class=\"coin\">T</div>";
}
}
echo "<p>It took {$flipCount} flips!</p>";
?>
</body>
</html>
While Loop Syntax(2/7)
In the last exercise, you saw how a while loop can be used to repeat a set of commands an unknown number of times. That loop used the following syntax:
while(cond) {
// looped statements go here
}
where the statements in side the curly braces { and ``}are executed as long as the conditioncondis evaluated as true. In the last exercise,condwas the condition that the number of consecutive heads was less than 3:$headCount < 3```.
It is important when writing loops to make sure that the loop will exit at some point. The loop
while(2 > 1){
// Code
}
will never exit and is an example of an infinite loop. Avoid infinite loops like the plague! This is why we need to include $loopCond = false; in line 12. If you submit an infinite loop in one of these exercises, you will need to reload the page to stop it.
Instructions
Check out the while loop on line 9.
- On line 9, add a condition inside the parentheses
( )that makes the while loop run as long as$loopCond == true - Inside the curly braces, use
echoto output"<p>The loop is running.</p>" - Then click Save & Submit Code to run your first PHP
whileloop!
Hint
Your while loop should look something like this:
while($loopCond == true) {
echo "<p>The loop is running.</p>";
}
index.php
<!DOCTYPE html>
<html>
<head>
<title>Your First PHP while loop!</title>
</head>
<body>
<?php
$loopCond = true;
while($loopCond == true){
echo "<p>The loop is running.</p>";
//Echo your message that the loop is running below
$loopCond = false;
}
echo "<p>And now it's done.</p>";
?>
</body>
</html>
Your First While Loop(3/7)
Now it is time for you to write your own while loop from scratch. Maybe you could reproduce the behavior of one of your for loops from the previous course, or you could try to write your own coin flip program. The beauty of programming is that you can do whatever you want!
Unless you want to write an infinite loop on purpose (which you don't!), do not write infinite loops! And if you find you have submitted one, refresh the page to stop it.
Instructions
Write the code for your own while loop below the comment inside the<?php ?> tags. Then click Save & Submit Code to see the results of your loop.
Hint
If you're having some trouble thinking of something to do, try taking this while loop that counts from zero to three:
$loopCount = 0;
while ($loopCount<4){
echo "<p>Iteration number: {$loopCount}</p>";
$loopCount ++;
}
and making it start at two and count the even numbers up to and including eight.
index.php
<!DOCTYPE html>
<html>
<head>
<title>A loop of your own</title>
<link type='text/css' rel='stylesheet' href='style.css'/>
</head>
<body>
<?php
$loopCount = 0;
while ($loopCount<4){
echo "<p>Iteration number: {$loopCount}</p>";
$loopCount ++;
} //Add while loop below
?>
</body>
</html>
Using Endwhile(4/7)
PHP offers the following alternative syntax for while loops:
while(cond):
// looped statements go here
endwhile;
Note the colon after the end parenthesis and the semicolon after the endwhile statement.
When they are embedded in HTML, loops that use this endwhile syntax can be more readable than the equivalent syntax involving curly braces.
while(cond) {
// looped statements go here
}
Feel free to use whichever syntax you prefer... except on this exercise!
Instructions
Convert your while loop from the last exercise into endwhile syntax. Then click Save & Submit Code to make sure your new loop works just like the old one.
Hint
Replace { with : and } with endwhile;.
index.php
<!DOCTYPE html>
<html>
<head>
<title>A loop of your own</title>
<link type='text/css' rel='stylesheet' href='style.css'/>
</head>
<body>
<?php
$loopCount = 0;
endwhile ($loopCount<4){
echo "<p>Iteration number: {$loopCount}</p>";
$loopCount ++;
} //Add while loop below
?>
</body>
</html>
How Do You Do-While?(5/7)
You may have noticed that a while loop checks the loop condition before each iteration of the code inside. A logical alternative is to check the condition after each iteration before looping back. A do/while loop does just that. One consequence of this difference is that the code inside a while loop can be bypassed entirely whereas the code inside a do/while loop will execute at least once.
This means that the loop condition can depend exclusively on code within the loop's body. This is the case for the code in the editor where each iteration represents a coin flip, and any time the result of the coin flip is tails, the loop stops.
Instructions
Inspect the code within the editor to see if you understand how it will work. If you don't, no worries! Click Save & Submit Code and see what happens.
Hint
The do/while loop sytax, which will be discussed in the next exercise, looks like this:
do {
// looped statements go here
} while (cond);
In this example, $flip is either 1 or 0, which means it works as a boolean true or false variable as well. (When used as a condition,1 means true and 0 means false to PHP.)
The syntax "StringStuff {$var} MoreStringStuff" is an efficient way to add a variable $var into a string.
index.php
<!DOCTYPE html>
<html>
<head>
<link type='text/css' rel='stylesheet' href='style.css'/>
<title>More Coin Flips</title>
</head>
<body>
<p>We will keep flipping a coin as long as the result is heads!</p>
<?php
$flipCount = 0;
do {
$flip = rand(0,1);
$flipCount ++;
if ($flip){
echo "<div class=\"coin\">H</div>";
}
else {
echo "<div class=\"coin\">T</div>";
}
} while ($flip);
$verb = "were";
$last = "flips";
if ($flipCount == 1) {
$verb = "was";
$last = "flip";
}
echo "<p>There {$verb} {$flipCount} {$last}!</p>";
?>
do {
// looped statements go here
} while (cond); </body>
</html>
Completing the Loop(6/7)
In the previous exercise, you saw how a do/while could be used to ensure that the code in a loop executed at least once. For example:
<?php
$i = 0;
do {
echo $i;
} while ($i > 0);
?>
Thisdo / while loop only runs once and then exits:
- First we set
$iequal to0. - Second, the loop runs once and outputs
$i, which is0. - Then the condition
while ($i > 0);is checked. Since$iis not greater than 0, the condition evaluates tofalse, and thedo/while` loop stops.
Instructions
Starting on line 9, there is a do / while loop that should run only once and then exit. But it's missing curly braces { }, parentheses ( ), and semicolons ;.
- Fill in the missing
{ },( )and;to make sure thedo/whileloop runs correctly. Check out thedo/whileloop above for an example. - Then click "Save & Submit Code" and verify that the page looks the way you expected.
Hint
You will need to fill in the following characters: {,}, (, ), ;, and ;, but not necessarily in that order.
index.php
<!DOCTYPE html>
<html>
<head>
<title>Much a do-while</title>
</head>
<body>
<?php
$loopCond = false;
do{
echo "<p>The loop ran even though the loop condition is false.</p>";
}while ($loopCond);
echo "<p>Now the loop is done running.</p>";
?>
</body>
</html>
All On Your Own!(7/7)
Now it is time for you to write your own do/while loop. You could try to implement one of your for or while loops using a do/while structure, or you could try something completely different.
But whatever you do, please do not write an infinite loop. And if you do submit one, refresh the page to stop it.
Instructions
Create a do/while loop below the comment within the <?php ?> tags in the editor. Then click Save & Submit Code to make sure it behaves the way you think it should.
Hint
If you're having trouble thinking of what to do and you're looking for a challenge, you could try a variation on the coin flipping loop in exercise 5. This time, roll a six-sided die until you get a six!
To do this, you will need to assign rand(1,6) to a variable $roll and then continue the the loop on the condition $roll != 6.
Make sure you echo $roll in some way so you know if the loop is working.
index.php
<!DOCTYPE html>
<html>
<head>
<title>Your own do-while</title>
<link type='text/css' rel='stylesheet' href='style.css'/>
</head>
<body>
<?php
while ($flip);
$verb = "were";
$last = "flips";
if ($flipCount == 1) {
$verb = "was";
$last = "flip";
}
echo "<p>There {$verb} {$flipCount} {$last}!</p>";
?>
do {
// looped statements go here
} while (cond); //write your do-while loop below
?>
</body>
</html>