Control Flow Keywords in PHP Loops

Too frequently I see PHP code that treats looping constructs (e.g. for, foreach, while) like runaway trains. Terminal conditions are set before entering the loop, but once the loop is started, it's all hands off until it finishes.

Unless there is an express need to iterate over every value, control flow keywords should be used to limit iterations. The most common of these is break, causing the loop to terminate when it is encountered.

Less common control flow keyword is continue. It too stops the current iteration, but instead of exiting the loop it simply begins the next loop iteration.

Depending on the situation, judicious use of continue and can prevent unneeded computation, flatten nested if statements, and increase code readability.

Finally, both break and continue take an optional numeric argument. Inside multiple nested loops, the argument defines how many looping constructs the command bubbles up.

Comments