PHP Character Iteration In For Loop Issue [duplicate] PHP Character Iteration In For Loop Issue [duplicate] php php

PHP Character Iteration In For Loop Issue [duplicate]


Straight from the PHP Manual:

PHP follows Perl's convention when dealing with arithmetic operations on character variables and not C's. For example, in PHP and Perl $a = 'Z'; $a++; turns $a into 'AA', while in C a = 'Z'; a++; turns a into '[' (ASCII value of 'Z' is 90, ASCII value of '[' is 91). Note that character variables can be incremented but not decremented and even so only plain ASCII characters (a-z and A-Z) are supported. Incrementing/decrementing other character variables has no effect, the original string is unchanged.

The reason it keeps going is because you're attempting a numerical comparison (<= and AA < Z, ZA == Z (when doing <=)) instead of a literal value comparison (==).

In light of this, you could use the following code:

for ($c = "A"; $c != "Z"; $c++){    echo $c . ", ";}

.. or use the actual ordinal value of the characters (which is the better solution in my opinion):

for ($c = ord("A"); $c <= ord("Z"); $c++){    echo chr($c) . ", ";}


Don't use < or > (or >= or <=) for comparisons when incrementing characters, use !==

for ($c = "A"; $c !== "AA"; $c++){    echo $c.", ";}

where the 'AA' is "one higher than" the endpoint you want

$lastCharacter = 'Z';$lastCharacter++;for ($c = "A"; $c !== $lastCharacter; $c++){    echo $c.", ";}

All words comprised of ASCII characters (the range A-Z) will be <= 'Z' until you get to ZA, because the compasrison is a string comparison, and "AA" is < "Z" if the strings are sorted. See my answer to a previous version of this question


Congrats, you found one of the many inconsistencies in PHP. In short: the + and < operators work totally different on strings.

  • increasing a single-letter string works as you would expect
  • increasing Z results in AA and so on (think about Excel columns)
  • comparing single-letter strings works as you would expect
  • comparing multiple-letter strings works lexicographically (letter by letter)

Now the interesting edge case is:

'Z' <= 'Z'    // because equal'Z'++ == 'AA' // because magic'AA' <= 'Z'   // because A comes before Z