Main Content

While, for, foreach or something else to loop.

Archive - Originally posted on "The Horse's Mouth" - 2012-11-06 23:47:28 - Graham Ellis

Newcomers to programming often ask "which loop should I use?"

Every language has a while loop, most have a for loop (though sometimes those differ in what they do - Python is an exceptional one, for example), and many have a foreach loop. Then you get the odd ones such as the until loop in Perl ...

A while loop is at the "lowest level" - you can always do what you want with that, but it may be a bit wordier than you wish in coding, and that may make it a bit more prone to coding with errors ("bugs"), and it may make it harder for someone coming along later to update your code to understand what's going on.

On yesterday's PHP course, I took an example of an array that I wanted to print our element by element ...

Using a while loop, I have separate statements to set the position number in the array that I'm starting at, to check the end, and to step up the counter (to the array) by one:

  $at = 0;
  while ($at < count($info)) {
    print "w: $info[$at]\n";
    $at++;
    }


With a for loop, I take my initial position setter and my stepper and move them into the controlling for statement, making the code much easier to follow, but not really reducing the code elements:

  for ($at = 0; $at < count($info); $at++) {
    print "f: $info[$at]\n";
    }


If I don't need to know the position number (don't want to print it out, or look back to the "previous", forward to the "next", then I can do completely without the position variable (called $at in my example) using a foreach loop:

  foreach ($info as $fruit) {
    print "g: $fruit\n";
    }


Complete example - [here]. PHP courses - [here].