SQL PHP HTML ASP JavaScript articles and free scripts to download
 

PHP For & foreach looping

For loop in PHP is used to iterate through a section in an application. This is used frequently in many applications. Different requirements can be achieved like breaking the loop based on some condition by using break statement etc can be added. We will start with a basic loop and then move to adding different requirements to it. Here is the basic syntax for for loop.
for($i=1; $i<=10; $i++){
echo $i."<br>";
}
This will list from number one to ten. In above case the loop is executed 10 times and each time the value of $i is increased by 1. So in the first loop the value of $i became 1 and in the last loop the value equals to 10. Next time when the value of $i becomes 11 the condition checking fails and the loop is escaped without executing. Here condition is checked at the staring of the loop.

Now we will try with a break statement in side the for loop. By using break we can exit the loop without completing the total required loopings (early exit).
for($i=1; $i<=10; $i++){
if($i > 5){break;}
echo $i."<br>";
}
This will list from 1 to 5 only. The If condition inside the for loop will exit the loop when the value of $i exceeds 5 ( that is when it equals to 6)

Step value of increment in loop

So far we have seen each time the variable value is increased by 1. This increase or step value can be changed. Now we will use a step value of 10 so the variable $i will increase its value by 10 ( it was increasing by 1 in previous cases ) in each looping.
for($i=0;$i<=100;$i +=10){
echo $i."<br>";
}
The above code will display 0,10,20 ... till 100

While handling PHP Arrays foreach function is required to display the elements of an array. Once the foreach function is called the array pointer will reset to the first element of the array. So we need not call the reset() again( Reset() rewinds array’s internal pointer to the first element. ). Here is an example of the foreach code.
$i = array (10, 12, 13, 25);
foreach ($i as $v) {
print "Present  value of \$i: $v <br> ";
}
This will list all the values of the array from starting to end. You can read more on arrays
Read how to display elements of an array



Further readings
Loops and program structure of PHP scripts
switch
For Loop
if else condition checking
while loop
Do while loop

vinit03-05-2013
How to use loop in the form of next if i am click on browser?
Post Comment This is for short comments only. Use the forum for more discussions.
Name
Email( not to be displayed)Privacy Policy
1+2=This is to prevent automatic submission by spammers. Please enter the result of the sum as asked

Join Our Email List
Email:  
For Email Newsletters you can trust
Basic Loops
HTML . MySQL. PHP. JavaScript. ASP. Photoshop. Articles. FORUM Contact us

©2000-2013 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer