PHP repetition control structures

Website Theme

PHP repetition control structures

September 1st, 2012

A control structure is block of code that is executed based on a condition. A repetition control structure repeats program statements based on the evaluation of a condition. PHP has the following repetition control structures:

  • For loop
  • Foreach loop
  • While loop
  • Do while loop

Let’s take a look at how each of these repetition control structures function.

For Loop

The for loop repeats a set of program statements based on a counter variable. For example:

for( $1  = 0; $1 < 4 ; $i++ ) {
 //body of for loop

In the above for loop the counter variable $i is first initialized to 0. Then on each iteration of the loop two things take place:

  • It checks if the value of $i is less than 4. If true the loop will continue. If false the loop will stop.
  • It increments the value of $i by one ($i++)

So the above for loop will run 4 times i.e. the statements in the body of the loop will execute 4 times. It is possible to access $i from within the body of the for loop. For example:

for( $i = 0; $i < 4; $i++ ) {
 echo "$i <br>";

The above code displays the value of $i in each iteration of the for loop. So it will display 0, 1, 2 etc. separated by line breaks.

Foreach loop

The foreach loop is designed specifically to iterate over the elements of an array. So for example:

$arr = array( 'blue', 'green', 'red', 'yellow', 'purple' );
foreach( $arr as $colour ) {
 echo "$colour <br>";

In each iteration of the above foreach loop $colour takes the value of an element of the array starting from the first element and ending at the last. So the above code will display the colours in the array once per line.

It is also possible to iterate over associative arrays:

$arr = array( 'sky'   => 'blue', 
              'water' => 'clear', 
              'mud'   => 'brown', 
              'grass' => 'green',
              'sun'   => 'yellow'
foreach( $arr as $thing => $colour ) {
 echo "$thing is $colour coloured <br>";

In each iteration $thing will have the key of the array element while $colour will have the array element’s value. So the above code will display statements like “sky is blue coloured” once per line.

Next we look at while and do while loops.

Pages: 1 2

Comments are closed.

Domain for sale

This domain name is for sale. If you are interested in buying it please contact me.