Lesson 3.9. PHP loops


There are three loops in PHP (as in C):

Here are some examples with each loop. Each example count from 0 to 10:

For loop example

for ($i=0 ; $i<=10 ; $i++) echo $i.' ';

While loop example

while ($i<=10) { echo $i.' '; $i++; }

Do .. while loop example

  echo $i.' ';
while ($i<=10);

The foreach loop

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:

$_SERVER in HTML table

See also

Last update : 03/10/2022