There are three loops in PHP (as in C):
for
loopwhile
loopdo ... while
loopHere are some examples with each loop. Each example count from 0 to 10:
for ($i=0 ; $i<=10 ; $i++) echo $i.' ';
$i=0;
while ($i<=10) { echo $i.' '; $i++; }
$i=0;
do{
echo $i.' ';
$i++;
}
while ($i<=10);
The last loop (foreach
) is propably the most used in PHP. The foreach
loop
allows to iterate over an array without creating an index variable. This loop
is very usefull to iterate over DB queries results:
// Create a table
$array = array( 10 => 'ten', 20 => 'twenty', 30 => 'thirty');
// Iterate over the array
foreach ($array as $value)
echo $value.'<br>';
The foreach
loop allows you to browse the values of the array as in
the example above. But keys (or indexes) can also be retreived with this syntax
foreach ($ array as $ cle => $ value)
. Here is an example :
foreach ($array as $key => $value)
echo $key . ' in written ' . $value.'<br>';
Write a PHP script that display the $_SERVER
variable in a HTML table. Here is the
expected result: