How Computers Get to Sleep at Night

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.

3 thoughts on “How Computers Get to Sleep at Night

  1. cliff claven says:

    Professor Ben, is the correct answer?


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

  2. cliff claven says:

    Wait, wait, I’ve got it now:


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

  3. 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 Reply

Your email address will not be published. Required fields are marked *