Php Loops Tutorial
Loops are used in php to perform an action many times. For example, we want to display our name 100 times on a webpage. Instead of typing it 100times, we can use a loop. Loop will display it 100times.
PHP FOR LOOP
for(start; condition; increment ){
// Code to repeat 10 times
}
<?php
//start, condition, increment for loop
for($i=1; $i<=10; $i++)
{
//display this message
echo $i . ". shahid <BR> <HR>";
}
?>
An example script that uses for to print out the 7 times table:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>The 7 Times Table</title> <link rel="stylesheet" type="text/css" href="/~cs1spw/tutorials/blue.css"> </head> <body> <h1>The 7 Times Table</h1> <ul> <?php for ($i = 1; $i <= 10; $i++) { echo "<li>$i times 7 is ".($i * 7)."</li> "; } ?> </ul> </body> </html>
PHP WHILE LOOP
start;
while(condition)
{
// Code to repeat until condition is false;
increment;
}
<?php
//Start counting
$count = 1;
//a condition for while loop
while($count <= 10)
{
//display this message
echo $count . ". this is while loop<BR>";
//increment value of count by one
$count++;
}
?>
PHP For Each Loop
foreach ($array as $key => $value) {
echo "$key: $value";
}

