PHP PHP Arrays and Control Structures PHP Loops Do While Looping

Radoslaw Proscewicz
Radoslaw Proscewicz
2,675 Points

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
201,932 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.