PHP Loops

PHP supports all the common control structures for looping including while, do-while, for, and foreach. Generally these all work exactly the same as they do in other languages.

One thing to watch out for when using foreach is that the value field that you specify for it to use to hold the particular content of each iteration through the loop will continue to exist after the loop ends and will still hold the last entry from the loop. You may want to unset the field after the end of the loop so as to keep things clean.

Loops are of course often used for processing arrays and PHP contains a number of array methods that change the current position within an array and so you need to be aware of the effect that these might have on your loop processing.

PHP also supports the same alternative format using a colon to start the loop and an end statement to end the loop as is available for if and switch statements.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow