Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
215,269 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