The for Statement

Strictly speaking, the for loop is unnecessary. Any for loop can be implemented as easily as a while loop. What for offers is not new functionality, but a better structure for building the most common loops. Many loops involve incrementing a counter variable every time through the loop, iterating until some maximum is reached.

Imagine that you wanted to step through the numbers 1 through 10. Using while, you would first set a variable to be 1. Then you would make a while loop that tests if your counter is less than or equal to 10. Inside the code block you would increment your counter, making sure you do this as the last statement in the block.

The problem is that it is very easy to forget to put the increment in. The result ...

Get Core PHP Programming: Using PHP to Build Dynamic Web Sites now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.