3

So I was doing some exercises and ran across this code (which produces "1. Item A", "2. Item B", etc ):

echo "\n<ol>";
for ($x='A'; $x<'G'; $x++){
    echo "<li>Item $x</li>\n";
}
echo "\n</ol>";

Curious, I attempted to do the reverse (which produces an infinite loop of Zs):

echo "\n<ol>";
for ($x = 'Z'; $x > 'M'; $x--){
    echo "<li>Item $x</li>\n";
}
echo "\n</ol>";

What have I missed here?

Tim Spencer
  • 131
  • 7
  • for whatever reason, `--` doesn't work on string characters. and incrementing a character should technically be considered a bug. consider that `$x++` is the same as `$x = $x + 1;`, so in you're doing `$x = 'A' + 1;` and `$x = 'Z' - 1`, both of which SHOULD evaluate to `0`, when the chars get cast to integers. – Marc B Nov 16 '15 at 21:16

1 Answers1

4

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 alphabets and digits (a-z, A-Z and 0-9) are supported. Incrementing/decrementing other character variables has no effect, the original string is unchanged.

from PHP manual link

orestiss
  • 2,183
  • 2
  • 19
  • 23