PHP Loops
This page teaches you about PHP loops.
Loops are used in PHP to execute the same code again.WHILE
The WHILE statement will execute a code if and as long as a condition is true. Once the condition becomes false the loop is stopped.Syntax while ( conditional statement is true)
{
do this
}
PHP Page
|
<html> <head> <title>HTML tutorial</title> </head> <body> <?php $i=1999; while($i<=2006) { echo "The year" . $i . " was a great year.<br>"; $i++; } ?> </body> </html> |
||
This is how it looks
|
The year 1999 was a great year. The year 2000 was a great year. The year 2001 was a great year. The year 2002 was a great year. The year 2003 was a great year. The year 2004 was a great year. The year 2005 was a great year. The year 2006 was a great year. |
||
DO WHILE
The DO WHILE statement is like the WHILE statement except that it will execute specific code at least once and continue the loop as long as a condition is true. The syntax is:Syntax do
{
this code;
}
while (condition);
PHP Page
|
<html> <head> <title>HTML tutorial</title> </head> <body> <?php $i=1999; do { $i++; echo "The year" . $i . " was a great year.<br>"; } while($i<=2006) ?> </body> </html> |
||
This is how it looks
|
The year 1999 was a great year. The year 2000 was a great year. The year 2001 was a great year. The year 2002 was a great year. The year 2003 was a great year. The year 2004 was a great year. The year 2005 was a great year. The year 2006 was a great year. The year 2007 was a great year. |
||
FOR
The FOR statement is used when you know how many times you want code executed. It is a Loop with a limited number of executions. The statement has three parameters. The first parameter initializes any variables (if you have more than one variable they should be seperated by commas), the second parameter holds the condition, and the third parameter contains the increments of the loop.Syntax for (initiale; condition; increment)
{
this code;
}
PHP Page
|
<html> <head> <title>HTML tutorial</title> </head> <body> <?php for ($year=2000; $year<=2007; $year++) { echo $year; echo " is during the new millenium."<br>; } ?> </body> </html> |
||
This is how it looks
|
2000 is during the new millenium. 2001 is during the new millenium. 2002 is during the new millenium. 2003 is during the new millenium. 2004 is during the new millenium. 2005 is during the new millenium. 2006 is during the new millenium. 2007 is during the new millenium. |
||
FOREACH
The FOREACH loop will keep going through the loop until it has gone through every item in the array.Syntax foreach (key => value)
{
execute this code;
}
PHP Page
|
<html> <head> <title>HTML tutorial</title> </head> <body> <?php $person[dave] = "1973"; $person[brian] = "1958"; $person[joe] = "1992"; foreach( $person as $name => $birthyear) { echo "$name. Age: $birthyear<br>"; } ?> </body> </html> |
||
This is how it looks
|
dave. Age: 1973 brian. Age: 1958 joe. Age: 1992 |
||
Bookmark this page: |








