A do
…while
loop is very similar to a while
loop. The main difference is that the code block will execute once without the conditional being checked. After the first iteration, it behaves the same as a while
loop.
The syntax is slightly different, and the conditional goes at the end of the code block. Our counting to 10 example looks like:
$count = 1; do { echo "The count is: " . $count . "\n"; $count += 1; } while ($count < 11);
Unlike the other loop types, the do
…while
loop requires a semicolon at the end.
In practice, only use this type of loop when you always need the code block to execute at least one time.
For example, if you want to ask a user to guess a secret number, you could use code like:
<?php do { $guess = readline("\nGuess the number\n"); } while ($guess != "42"); echo "\nYou correctly guessed 42!";
This code asks the user to "Guess the number"
and continues asking them until they successfully guess 42.
Instructions
For this exercise, we have a plant. We’ve initialized its height using the variable $plant_height
to 22. Using a do
…while
loop, you will be growing the plant by 1 every loop increment. When the plant reaches a height of 30, it is mature and starts producing fruit. At this point, we want to notify the user and exit from the loop.
Begin by establishing an empty do
…while
loop after the $plant_height
initialization. It should continue while the plant is less than or equal to 30. Be sure to increment $plant_height
on each loop iteration or you may have an infinite loop!
At the beginning of each loop iteration, we should notify the user of the plant’s height. Add a statement to print "The plant is [X] tall."
, with [X]
replaced with the current value of $plant_height
. Be sure to add a newline after every print statement.
Add an if
statement within the loop. When the plant is greater than or equal to 30, you should print "And can produce fruit."
.
Now you can see the usefulness of the do
…while
construct here.
Try changing the initial height to something greater than 30. You will still get notified of the plant’s height and maturity, even though the condition is not met.