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

Stop when reach 0 from 10

Hi, how can i stop this code to when it arrives to 0 ?

'''PHP <?php

$number = 10;

while ( $number<= 10) { echo "$number <br>"; $number--; }

?> '''

3 Answers

Aurelian,

This is simpler using a for loop, but if you need to use a while loop:

$number = 10;

while ( $number >= 0) { 
    echo "$number "; 
    $number--; 
}

Or, better:

for ($number = 10; $number >= 0; $number--)
{
  echo $number; 
}

Oh yes but imnot that far yet . Im learning step by step , i know i could use for loop because i just finished all the for , while etc.. but at the moment im just learning parts by parts :) But thank you very much for this answer too :) ill come back to it when ill need it :) i really appricate your help too :) thank you

Ricky Catron
Ricky Catron
13,023 Points

Change your $number <= 10 to $number >= 0. That should fix everything.

Ricky, that just recreates the problem in reverse--it doesn't stop at 10 (unless he doesn't need to stop at 10, I suppose).

Ricky Catron
Ricky Catron
13,023 Points

He needs to stop at 0 not 10. He is trying to count down but his while check is prepared for counting up.

Okay this works :) Thank you everyone for responses :)

Aurelian,

You could use an AND statement ("while $number is <= 10 AND > 0) or you could increment (++) rather than decrement, and change your variable to start at zero. Or, you could change your while's condition.

Yes but the problem is that i want to start from 10 and stop at 0 . It goes infinity when i run that code. If i put ++ and i start at 0 , it will go from 0 till 10 but i want to go from 10 to 0 and stop . And whatever else i do , the code crash.

Im waiting for PHP Basics and well, cant wait for them , in case they come up in a month , ill learn PHP basics faster than they come out xd so ill be one month ahead.