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

While Loops in PHP Forum

View Course » View Exercise

322 points
A46ce5419272b76c77f365d388de0dde?s=140&d=retro
Submitted by
Daniel Campbell
over 2 years ago

PHP: Using Endwhile 4/7

Can anyone tell me why this won't work

<!DOCTYPE html>


A loop of your own



<?php
//Add while loop below
$loopCount = 2;
while ($loopCount< 9):
echo "Iteration number: {$loopCount}";
$loopCount + 2;
endwhile;
?>

It comes up the error message: The program took too long to finish. Check your code for infinite loops and try again.


1 vote

permalink

Daniel, the problem is in incrementing the variable.
To increment by 1, $variable++ is a shortcut (same as $variable = $variable + 1)
To increment by 2: $variable = $variable + 2;

$loopCount + 2; does not increment the variable - what happens is that the variable itself remains the value of 2, which is less than 9, so you have an infinite loop.

A simple way to check is to add 'break;' before closing. That will stop an infinite loop and you can see what's echoed before it stops.

Here's your code with the changes:
(I added html paragraph tags so formatting)

$loopCount = 2;
while ($loopCount < 9):
echo "Iteration number: {$loopCount}";
$loopCount = $loopCount + 2;
endwhile;

Try this to see the effect of using break on an infinite loop

$loopCount = 2;
while ($loopCount< 9):
echo "Iteration number: {$loopCount}";
$loopCount + 2;
break;
endwhile;

134 points
10622d072c3aaa04ad7c84286cfbe98d?s=140&d=retro
Submitted by
demediaMes
over 2 years ago

1 Comment

A46ce5419272b76c77f365d388de0dde?s=140&d=retro Daniel Campbell over 2 years ago

Thanks It worked


0 votes

permalink

try
<?php
$loopCount = 0;
while ($loopCount<8):
echo "Iteration number: {$loopCount}";
$loopCount ++;
endwhile;
?>

91 points
B401d1ef814c4f5b14d6df88189a074d?s=140&d=retro
Submitted by
Boris2412
over 2 years ago