Ways to write a loop in PHP

Loop is the essence of everything. So you should know each and every way how you could write a loop in a PHP language. Lets start - ways to print numbers in a range [0..9]

1. FOR

1.1 Looping with loop iterator

for ($i1=0; $i1<10;$i1++) {
  echo $i1;
}

1.2 Looping through elements of array

foreach (range(0,9) as $i2) {
  echo $i2;
}

2. WHILE

2.1 While - Do construct

Usually is used when exact number of iterations is not known, but we know loop condition well. Loop body is not started if it's condition is not satisfied at the beginning of loop

while ($i3++ < 10) { 
  echo $i3-1;
}

2.2 Do - While construct

Basically the same as above. The only difference is that loop's body is executed at least once.

do { 
  echo (int)$i4; 
} while (++$i4 < 10);

3. GOTO

Many says that it's a bad style to use goto statement. Well, maybe yes, maybe no. But nobody can't deny the fact that goto can help you to terminate legacy code unneeded branch without refactoring it with 100 business days penalty. Same for a loop- sometimes it's faster to make a repeating legacy code with goto statement :

LOOP_START:
echo (int)$i5;
if (++$i5 < 10) {
  goto LOOP_START;
}

4. RECURSION

4.1 Direct recursion

When a function calls itself.

function rec($i) {
  if ($i < 10) {
    echo $i;
    rec($i+1);
  }
}
rec(0);

Just be cautious - it's very easy to write a non-terminating loop which eats all memory stack.

4.2 Indirect recursion

When there is a calling cycle between several functions. A()->B()->A().

function reca($i) {
  if ($i < 10) {
    echo $i;
    recb($i+1);
  }
};
function recb($i) {
  reca($i);
};
reca(0);

5. SELF-INCLUDE

This one is just for fun :-)

Create a file with name incloop.php. Which would have a contents :

if ($x++ < 10) {
  echo $x-1;
  include __FILE__;
}

Now in external place, where you want this type of loop to happen, just write :

include 'incloop.php';

There is no magic here. Just keep in mind that include is simply a copying of source file contents into destination file contents. So actually this type of loop is a form of meta-programming,- loop is done by a PHP interpreter.

Have fun using different loops ! :-)

No Comments Yet