• Programming 19.09.2008

    There are two good ways to iterate over an array in PHP.  One is the classic syntax found in some form in all modern procedural languages:

    for ($i = 0; $i < count($colleges); $i++) { ... }

    There’s also this straightforward variant, also found in a lot of languages now:

    foreach ($colleges as $college) { ... }

    Given these two loops, under no circumstances is the following acceptable:

    $i = 0;
    while($i != (count($colleges) - 1)) { ... $i++; ... }

    Besides being unnecessarily verbose, this will also never terminate if the array is empty.  Eventually the server will get bored of counting up one integer at a time and forcibly kill the script, but that just means users will have to call me to fix it.

    In conclusion, please don’t let student developers touch any more of my production code.

    Posted by Ben @ 9:06 pm

  • 3 Responses

    WP_Modern_Notepad
    • cliff claven Says:

      Professor Ben, is the correct answer?


      $i = 1;
      while (!($i > count($colleges))
      { $college = $colleges($i - 1); ... $i += 1; }

    • cliff claven Says:

      Wait, wait, I’ve got it now:


      $i = count($colleges);
      while ($i > 0)
      { $college = $colleges(count(colleges$ - $i);
      $i = $i - 1;
      }

    • cliff claven Says:

      Forget what I said before. This is the real answer:


      $i = 0 - count($colleges);
      while ($i < 0)
      { $college = $colleges(count(colleges$) + $i));
      $i = $i + 1;
      }

    Leave a Comment

    Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.