Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP PHP Arrays and Control Structures PHP Loops While Quizzing

Christian Chandler
Christian Chandler
3,116 Points

PHP Arrays and Control Structures quiz - do loop

The question in the quiz is below:

What would be displayed when the following code is executed?

$i = 0; do { echo "$i is greater than 2\n"; $i++; } while ($i > 2);

Will the while loop only display after it runs the first three times (until it is greater than two) and when will it stop?

Thanks

3 Answers

Antonio De Rose
Antonio De Rose
20,884 Points
<?php

$i = 0;//$i is 0 here
do {
echo "$i is greater than 2\n";//this will anyway print for the first time, as it had not met the condition.
$i++;//now the $i is 1
}
while ($i > 2);//checks the condition, exits from it.
//to answer your question, it will only print once, and the loop, would only run once, and not 3 times.
?>

I think because the condition is not met it will not run. 1 is not greater than 2. For the loop to run the condition $i is greater than 2 must be true. The only reason it runs is that there is a "do" loop/condition before the "while" loop/condition. The "do" condition will make something happen at least once before checking to see if the "while" condition is true. I hope that helps.

Seth Johnson
Seth Johnson
15,199 Points

I'm afraid this quiz question leaves me feeling more than a little lost as well; did I miss something about the explanation of a "while" loop that inherently exits the loop after a single instance? Any light that anyone can shed on this would help a lot. Thanks in advance. : )