Tuesday, 30 January 2007
Tutorial on Loops in PHP |
| |
|
| |
Haroon Ahmad over at the Howtoforge web site gives you information about loops and its uses in PHP. He explains that there are certain conditions in which you need to execute the same block of code again and again. He illustrates with an example that if you want to print ten consecutive equal signs in three lines to make a separator then you could do it with different methods. One such method is by using three echo statements and putting ten equal signs in each. An example is as follows:
He says if there are a small number of echo statements than it is easy to carry out the process. But if hundred such lines have to be printed that means it will require three hundred echo statements. So, loads of typing and hassles will come up to organize them. In that case loops can be used to write few lines, which will print more, output depending on the loops condition.
He gives an explanation about loops in PHP under the following heads:
Basic Concepts of Loop
He says braces {} are used to make block of code that you want to execute for a specific number of times. This is called the body of loop. Every loop depends on a condition. It keeps executing the block of code unless the condition is met true or stand false which depends on the loop type. But he says, there is a terminating point for each loop that ends the loop when the condition is satisfied. Like in the prior discussed example if you want to display hundred lines of ten equal signs each then you will have the following attributes to make up the loop in theory:
- Condition—hundred lines: keep printing unless hundred lines are printed
- Body of the loop: in which the printing stuff that is the echo statement is used to print equal signs and some additional contents that will help the loop to execute for the desired number of timing
- Terminating point: when hundred lines are printed the loop must terminate
- Loop run: every time the block of code (body of loop) executes the loop completes its one RUN
Types of loops
He lists out four types of loops that PHP offers with explanation for each. They are:
- FOR Loop: he provides the basic syntax for this loop and gives three attributes using the ‘for’ keyword followed by an explanation of loop variable.
- While Loop: he says this loop is indefinite loop because it works on mainly a condition that can stand true for unknown number of loop runs. An example is provided for better understanding of the term.
- Do-While Loop: Do-While loop will run the loop at least once before it checks the loop condition and hence it’s handy in the situation where we need to run the loop for the first time without checking the condition, he informs. This definition is followed by the basic structure of this loop.
- Foreach Loop: the fourth type of the loop in PHP is FOREACH loop which is used with Arrays, he says.
|
| |
|
Read the Article
|
| |
|
|
| |
|
|
| |
|