Basic Overview of Loops in PHP
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
while(expr) { // do stuff }
- Evaluate
expr - If
exprfalse, skip to 5 - Run code
- Repeat at 1
- 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.
// 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
do { // do stuff } while(expr);
- Run code
- Evaluate
expr - If
exprtrue, repeat at 1 - 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.
// 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
for(expr1; expr2; expr3) { // do stuff }
- Execute
expr1 - Evaluate
expr2 - If
expr2false, skip to 7 - Run code
- Execute
expr3 - Repeat at 2
- 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.
// 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
// 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.
// 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.
// 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.
Similar Posts:
- PHP: Process Array Items With array_map
- Data Storage with jQuery
- Generating (X)HTML Documents Using DOMDocument In PHP

September 25th, 2009 - 23:10
Foreach loop with reference(loop bellow) available only in php5
// Change each element to lowercase (using reference)
foreach($array as &$value) {
$value = strtolower($value);
}
Great post!
September 26th, 2009 - 10:31
Good point! I added a note about that being available since PHP 5.