PHP Looping
Last update on: 09-25-2008Loops allow you to browse a wealth of information stored in a table, a text file, a database and display them or treat them.
We have three type of looping functions:
while() for(); do...while() foreach() // PHP4 Only
I will give some examples of looping using this functions, but you will find more explanations in the next course, when we will start using them in our code.
exemple using while ():
$i= 0; // on define a variable and give the zero value to it. while ( $i <= 4 ) // the loop will stop when $i equal 4 { print 'round number '.$i.'<br />'; // we display this phrase with each current number of $i. $i++; // the ++ ($i= $i +1;) means that we add 1 each... //round of the loo, do not forget if else the... //loop will be infinite and it will show an error! }
On the Screen
round number 0
round number 1
round number 2
round number 3
round number 4
example using for():
or ($i=0;$i<=4;$i++) // it's the same example when we used (while),... //but the advantage of for() is you get all the code... //in the same line, that avoids the incrementing of the counter { print 'round number '.$i.'<br />'; // we display this phrase with the number of the round. }
On the Screen
round number 1
round number 2
round number 3
round number 4
example using do...while :
The following example will increment the value of i at least once, and it will continue incrementing the variable i as long as it has a value of less than 5:$i=0; do { $i++; echo "The number is " . $i . "<br />"; } while ($i<5); ?>
On the Screen
The number is 1
The number is 2
The number is 3
The number is 4
example using foreach():
The following example demonstrates a loop that will print the values of the given array:$arr=array("one", "two", "three"); foreach ($arr as $value) { echo "Value: " . $value . "<br />"; }
On the Screen
Value: one
Value: two
Value: three
You will find examples of loops and their uses in the following courses
To your keyboards and start typing and coding.
PHP and MySQL's lessons:
Introduction To PHPGet Started With PHP
PHP Variables
PHP Variables Of Environment
PHP Conditions
PHP Looping
PHP Cookies
PHP Working With Dates
PHP Working With Arrays
PHP Working With Files
PHP Play With Strings
PHP And Forms
Send Emails With PHP
The Include Statement
Get Started With MySQL
MySQL Update And Delete
The WHERE Clause
MySQL Functions
Guestbook Script
Websites Directory Script
Multiple Pages With PHP
Create Your Forum With Php

