How to use loops in php

Post Reply
User avatar
Neo
Site Admin
Site Admin
Posts: 2642
Joined: Wed Jul 15, 2009 2:07 am
Location: Colombo

How to use loops in php

Post by Neo » Sun Feb 28, 2010 11:34 pm

PHP comes with several control structures for creating loops. A loop is basically code that executes repeatedly for as long as it needs to. The control structures I'll discuss here are: while, do-while, for, foreach, break & continue. Each of these are similar, and some can pretty much be interchangeable, but some are better suited for certain tasks than others.

while

Code: Select all

while(expr) {
   // do stuff
} 
  1. Evaluate expr
  2. If expr false, skip to 5
  3. Run code
  4. Repeat at 1
  5. End loop
A while loop is the simplest to use. It runs the code as long as expr evaluates to true. The most common use for this structure is iterating through database results using something like mysql_fetch_assoc, which returns false once there are no more results. Below are some examples.

Code: Select all

// Prints 1 through 20
$i = 1;
while($i <= 20) {
   echo $i++;
}
 
// Prints the value of the 'foo' column for each row in the result
while($row = mysql_fetch_assoc($result)) {
   echo $row['foo'];
}
 
// Runs forever until a break statement is executed
//  (be careful with this)
while(true) {
   // do stuff
}
 
do-while

Code: Select all

do {
   // do stuff
} while(expr); 
  1. Run code
  2. Evaluate expr
  3. If expr true, repeat at 1
  4. End loop
This is identical to while with one minor difference: the expression is evaluated after each loop. This means that unlike while, do-while will always execute its code once regardless of the value of the expression. Below are some examples.

Code: Select all

// Prints 1 through 20
$i = 1;
do {
   echo $i++;
} while($i < 20);
 
// Runs forever until a break statement is executed
//  (be careful with this)
do {
   // do stuff
} while(true); 
for

Code: Select all

for(expr1; expr2; expr3) {
   // do stuff
} 
  1. Execute expr1
  2. Evaluate expr2
  3. If expr2 false, skip to 7
  4. Run code
  5. Execute expr3
  6. Repeat at 2
  7. End loop
The for loop is the most complex and flexible loop to use in PHP. There are three different expressions that are used, and each can contain multiple expressions (separated by commas) or be omitted entirely.

The first expression (expr1) runs once before the loop starts, so it is often used to initialize variables. The second expression (expr2) is evaluated before each loop, and ends the loop if evaluated to false. The third expression (expr3) runs after each loop, and is often used to increment/decrement a variable. Below are some examples.

Code: Select all

// Prints 1 through 99
for($i = 1; $i < 100; $i++) {
   echo $i;
}
 
// Prints each item in an array
//  note the $size is calculated only once to save performance
for($i = 0, $size = sizeof($array); $i < $size; $i++) {
   echo $array[$i];
}
 
// Example omitting the second expression
for($i = 0; ; $i++) {
   if($i > 99) {
      break;
   }
   echo $i;
} 
foreach

Code: Select all

// Example 1
foreach($array as $value) {
   // do stuff
}
// Example 2
foreach($array as $key => $value) {
   // do stuff
}
// Example 3 (PHP 5)
foreach($array as &$value) {
   // do stuff
} 
A foreach loop is only used with an array. It loops over each element in an array, passing its value to a local variable.

If you use the above Example 1, $value will contain a copy of the current array element's value.

Using the above Example 2, $key will contain the current element's key and $value will contain a copy of the current element's value.

Using Example 3, available as of PHP 5, $value will be a reference to the current element, and changing it within the loop will alter the original array.

Below are some examples.

Code: Select all

// This array will be used in all examples
$array = array('foo', 'bar', 'baz');
 
// Prints each array element
foreach($array as $value) {
   echo $value;
}
 
// Change each element to uppercase
foreach($array as $key => $value) {
   $array[$key] = strtoupper($value);
}
 
// Change each element to lowercase (using reference)
foreach($array as &$value) {
   $value = strtolower($value);
} 
break & continue
These two control structures do not create loops, but they are used to control the execution of loops. The break statement is used to force the loop to exit entirely. The continue statement causes the loop to stop the current iteration and skip to the next iteration. Both of these can accept a numeric argument to determine how many levels of nested loop structures to break or continue. Below are some examples.

Code: Select all

// Stops the loop
while(true) {
   break;
}
 
// Skip all empty array items
foreach($array as $value) {
   if(empty($value)) {
      continue;
   }
   // do stuff
}
 
// Stops the outer loop (2nd level up)
while(1) {
   while(true) {
      break 2;
   }
} 
Conclusion
This was a basic overview to loop structures in PHP. There is actually not much to them, yet they are so useful and powerful. Please comment if you have any suggestions for improvements or areas not covered.
Post Reply

Return to “PHP & MySQL”