Looping structures are one of the major aspects of programming languages. If you ever need to do something more than once, you really should consider using a loop.

There are four types of loops in PHP:

”’for”’ loop,

”’foreach”’ loop,

”’while”’ loop,

”’do while”’ loop,

= Common Loop Controls =

No matter which loop is utilized, they all share two major control constructs: * ”’continue”’ — skips the rest of the loop and continues with the next iteration. If a number is provided after it, it skips that number of iterations (this is hardly ever used). * ”’break”’ — stops the execution of the loop.

= For Loops =

The For Loop is the most common loop among the programming languages. PHP’s syntax is virtually identical to that of C, C++, Java, and C#, among others.

for (/initial command/; /test condition/; /command that runs after each iteration/) { // Code here }

By far the most common type of for loop is what is called the Counting Loop:

// 1. Initially, set $a to 1. // 2. Run the loop while $a is less than or equal to 3. // 3. After each loop, increment $a by one. for ($a = 1; $a <= 3; ++$a) { echo “$a - “; }

// Output: 1 - 2 - 3 -

// This is the equivalent of $a = 1; echo “$a - “; ++$a; echo “$a - “; ++$a; echo “$a - “; ++$a;

=== The wrong way to increment === Virtually every programmer increments variables incorrectly. Every book and every tutorial I have ever read does it incorrectly, as well. While it won’t matter much at all performance-wise, like good grammar, you’ll be looked on as being more intelligent by those who know how to increment correctly.


What this means is the following: $temp_variable = $a; $a += 1; return $temp_variable;

This creates the unnecessary steps of creating a temp variable, returning it, and then incrementing the original. There will hardly ever be a time when this is needed. In fact, in 15 years of programming, I have never run across such an instance.

=== The correct way to increment === ++$a;

What this means is the following: $a += 1;

= Foreach Loops = Foreach loops cycle through an array or [[PHPBook:Object Iteration|object AT]]. There’s not much to it.

$wins = array(‘Houston Rockets’ => 3, ‘Dallas Mavericks’ => 2, ‘New York Knicks’ => 5);

foreach ($wins as $team => $win_count) { echo “The $team have won $win_count times.\n”; }

/* Output: The Houston Rockets have won 3 times. The Dallas Mavericks have won 2 times. The New York Knicks have won 5 times. */

= While Loops =

While loops do something until the condition is true or the loop is broken out of (using ”’break”’). $data = array(5, 3, 8);

$sum = 0; while (!empty($data)) { $sum += array_pop($data); }

echo $sum; // Output: 16

= Do While Loops = Arguably the most useless of the loops, you should use a Do-While loop whenever you must run the code at least once:

$remaining = 5;

do { —$remaining; } while ($remaining < 5);