Thursday, January 22, 2009

Basics of looping in PHP

Loops are an integral part of PHP, and many other programming languages for that matter, the basics covered here would apply to javascript as well, even the code is very similar. A loop is simply a block of code that executes multiple times, controlled either directly, by explicitly telling the script to execute “X” times, or by using a variable, telling the script to execute “as many times as the exact hour at the time of viewing” for example.

So why do we use loops? There are hundreds and hundreds of reasons, the widest usage is probably to cycle through values of some sort of data. For example, you might be writing a messaging system in PHP, which would allow users of your website to send private messages to each other once they register. You would write a MySQL query which would pull all the user’s letter from the database. To show all the letters you would use a loop to show all the rows of the query (all the separate messages) on a page.

To create a loop you need to add some rules which will dictate how the loop should behave. Usually we need to give three values, the starting value of the counter (which tells the loop how many times it has executed), an ending value (which tells the script to stop looping if it is reached) and an increment, which deals with changing the starting counter value in some way (so that it eventually reaches the end value, hence ending the loop).

Read More..

No comments: