PHP repetition control structures

Website Theme

PHP repetition control structures

September 1st, 2012

While loop

The while loop executes program statements if a given condition is true.

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

The above code is an example of a while loop that functions pretty much like a for loop. First the variable $counter is initialized outside the loop to a value of 0. The on each iteration of the loop it checks whether $counter is less than four or not. If true it proceeds to execute the body of the loop where $counter is incremented by one and the value of $counter is displayed on-screen. So the above code will run 4 times and display $counter’s value each time.

Of course you can have any condition you like in the while loop and not just the evaluation of a counter variable’s value.

Do while loop

The do while loop functions like the while loop except for the fact that the conditional expression is evaluated at the end of the loop’s iteration. As a result the do while loop is guaranteed to run at least once.

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

As you can see in the above example the do while loop evaluates the condition at the end of the iteration. So the loop will run once and then it will find that $iterate is equal to false so it will stop running. The above code will display “This loop has run” once on-screen.

Break and continue statements

The break statement allows you to end a loop prematurely. For example:

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

The above code will display 0 to 3 on-screen. But when $count equals 4 the loop will be ended prematurely by the if block.

The continue statement allows you to continue program execution at the loop’s conditional evaluation statement. That is program execution jumps to the loop’s conditional evaluation statement. So for example:

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

In the above example the loop iterates 11 times. At each iteration the if block checks to see if the value of $counter is wholly divisible by 2 i.e. if $counter is an even number. If it is an even number it skips to the next iteration ( or more precisely to the condition evaluation portion of the for loop). If it is not an even number it displays it on-screen. So the above code will display all the odd numbers between 0 and 10.

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.