PHP Loops

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 100 times, we can use a loop. The loop will display it 100 times.

PHP FOR LOOP

A FOR loop requires three parameters:

  • start: the starting point, a value for the counter variable
  • condition: the condition that has to be met to run the loop again
  • increment: the counter has to be incremented (or decremented) before the loop is run again

for(start; condition; increment )
{
// Code to repeat
}

An example script that uses for to print out the 7 times table:

 

PHP WHILE LOOP

A WHILE loop will run a piece of code again and again until the condition becomes false. The code will be repeated only while the condition is true.

For a while loop you will need:

  • initialisation expression to be evaluated just once before the loop (start)
  • test expression to be evaluated each time the loop runs (condition)
  • loop body: the block of code to be repeated
  • iteration expression to be run after each loop execution (increment)

Please Note: without an increment you will have an infinite loop: it will never stop on its own. (fortunately modern browsers are able to stop them)

PHP DO-WHILE LOOP

A DO-WHILE loop can be used to execute the body at least once (the very first time) and it will have this syntax:

do
{
statement
} while(condition)

Here a working sample:

PHP For Each Loop

A FOREACH loop will allow you to iterate over elements in an array. You can use a foreach loop accessing each key of an array or both keys and values.

Accessing keys:

foreach ($array as $key){
echo “$key”;
}

 

Accessing keys and values:

foreach ($array as $key => $value) {
echo “$key : $value”;
}

Click here to read about PHP functions.