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 Do While Looping

Why would you increment a variable inside the condition portion of a while loop and not in the statement?

OK, I do not understand this while expression that was portrayed in this video: while (++$year <= $currentYear) { echo $year . "<br> \n"; I was always taught that the condition portion (the portion in parentheses) in any conditional, else, elseif, or while expression is only to specify the condition for the code or loop to run (true or false). You're not supposed to put any actual instructions or statements in there, to include increments. The actual code or instructions go in the statement section between the {}. Can anyone clear up this confusion? Thanks.

1 Answer

Steven Parker
Steven Parker
231,275 Points

The content of the "while" clause still constitutes an expression, it just happens that the evaluation of this expression causes the $year variable to be incremented. And this style of increment is performed before the comparison, which is not something that could be accomplished inside the loop body.

It might look a bit odd but it's actually a common technique used to make the code more concise.

That helps. Thank you