An Introduction to Loops in PHP

01
of 03

While Loops

In PHP, there are several different types of loops. Basically, a loop evaluates a statement as true or false. If it is true, the loop executes some code and then alters the original statement and starts all over again by re-evaluating it. It continues to loop through the code like this until the statement becomes false.

Here is an example of a while loop in its simplest form:

 

The code states that while a number is greater than or equal to 10, it prints the number. The ++ adds one to the number. This could also be phrased as $num = $num + 1. When the number becomes greater than 10 in this example, the loop stops executing the code within the brackets.

Here is an example of combining a loop with a conditional statement.

 "; 
 		} 
 	else 
 		{ 
 		print $num . " is not less than 5 
"; 
 		}	
 $num++; 
 	} 

 ?> 
02
of 03

For Loops

A for loop is similar to a while loop in that it continues to process a block of code until a statement becomes false. However, everything is defined in a single line. The basic structure for a for loop is:

for ( start; conditional; increment) { code to execute; }

Let's go back to the first example using the while loop, where it printed out the numbers 1 through 10,  and do the same thing using a for loop.

  

The for loop can also be used in conjunction with a conditional, just like we did with the while loop:

 "; 
 		} 
 	else 
 		{ 
 		print $num . " is not less than 5 
"; 
 		}	
 	} 

 ?> 
03
of 03

Foreach Loops

To understand foreach loops you have to know about arrays. An array (unlike a variable) contains a group of data. When using a loop with an array, instead of having a counter that goes until proven false, the foreach loop continues until it has used all values in the array. So for example, if an array contained five pieces of data, then the foreach loop executes five times. 

A foreach loop is phrased like this:

FOREACH (array as value) { what to do; }

Here is an example of a foreach loop:

 

When you understand this concept, you can use the foreach loop to do more practical things. Let's say an array contains the ages of five family members. A foreach loop can determine how much it costs for each of them to eat on a buffet that has varied prices based on age using the following pricing system: Under 5 is free, 5-12 years costs $4 and over 12 years is $6.

 "; 
 	} 
 print "The total is: $" . $t; 

 ?>