This forum is now read-only. Please use our new forums at discuss.codecademy.com.

While Loops in PHP Forum

View Course » View Exercise

412 points
E246db9647ace16f47ed3971df1784ea?s=140&d=retro
Submitted by
Alen Ramic
about 4 years ago

Why is the while code running when it's false

The code below is correct, but I don't understand it. The while condition reads while $loopCond is true, print "Now the loop....". Right? But the value of $loopCond is a fixed false, so why would it print that to the console?
Obviously I am not getting something. Any help would be greatly appreciated!

$loopCond = false;
do {
echo "The loop ran even though the loop condition is false.";}
while ($loopCond); {
echo "Now the loop is done running.";}


7 votes

permalink

You can split that code in two sections:

$loopCond = false;
do {
echo "The loop ran even though the loop condition is false.";}
while ($loopCond);

and

{
echo "Now the loop is done running.";}

The first one always runs one time. The second one is not subject to any condition, because it's outside of the do...while loop.

686 points
B3d6f7681a76849f5c3f732a257e1e9e?s=140&d=retro
Submitted by
andre.mendes
about 4 years ago

1 Comment

532afe767c82caf100002734_506113534 Thinnling over 2 years ago

My code works without having to put { }'s around, echo "Now the loop is done running." The brackets don't seem to be necessary.


0 votes

permalink

that's how do-while loops work, first it runs the code inside, Then it checks the condition, and repeats if it is true
while loops check before running, do-while loops check afterwards
you could think of while in terms of if, labels, and goto, as

:startLoop
if(not condition) goto endLoop
...
goto startLoop
:endLoop

and do-while would be

 :startLoop
    ...
    if(condition) goto startLoop

1051 points
5546eedc390fb11f2d498d38f21d12a4?s=140&d=retro
Submitted by
etn
about 3 years ago


0 votes

permalink

It would be very helpful if the condition was discussed a little more thoroughly. I got that with $loopCond = false PHP is assuming the only alternative is "true" making this a boolean but it's not intuitive and then following-up with "while($loopCond);" without explanation is a little much.

1298 points
219ab7f772efb1cd5440659fe629340a?s=140&d=retro
Submitted by
David Hollowood
over 2 years ago