Skip to content

How NOT to write a FOR loop in PHP

Dear Reader,

Ok, so I’m on a programming roll right now…sue me.

Here’s a piece of code I saw yesterday on a mailing list. At first I thought it was borked and started to reply that there’s no way it would work…son-of-a-gun if it doesn’t…sort of.

< ?php 
for ($j=A; $j <= Z; $j++) 
{
    echo $j."\n";
    if ($j==Z) break;
} 
?>

I’ve never seen anyone increment a character value before. It intrigued me so I played with it for a few minutes. First let me say if someone on one of my teams every wrote code like this…well, it’s a ‘Career Limiting Move’. Character values are just that, characters. If you need to build a list of the letters of the alphabet, do it the way programmers have been doing it for at least the 23 years I’ve been programming, iterate through the numbers 65-91. Use the chr() function to get your letter. (c’mon, other than the numbers changing, we even did that on my old C=64!)

The second problem with this code is that without the IF statement, that it doesn’t do exactly what you would expect it to do. Run the code without the IF and look at the output. I’m not sure I know why it does that. I’m not sure why $j does not evaluate to == Z when it actually displays the Z. I could probably dig in and find it but I really don’t care.

For those interested, a better way to do this would be:

< ?php 
for ($j=0; $j <26; $j++) 
{
  echo chr(65+$j)."\n";
} 
?>

It’s fewer lines of code and we are not using string types as numbers.

This is a good example of “Just because you can, doesn’t mean you should.”

Until next time, my prayers are with you today.
(l)(k)(bunny)
=C=