1

I noticed there is two different behaviors in PHP when we increment the alphabet:

Range:

range('a', 'Z');

output:

["a","`", "_", "^", "]","\", "[","Z"]

Which correspond to the ASCII table and make sense to me.

But when we increment with a for loop:

$letters = [];
for($i = 'a'; $i !== 'Z'; $i++){
    $letters[] = $i;
}

output:

[ "a", "b", "c", "d", ..., "x", "y", "z", "aa", "ab", "ac", "ad", "ae", "af", ...]

Why is php suddenly stuck with the letters 'a-z' instead of using the ASCII table?

And how does work the range method for not using this behavior?

Clément Baconnier
  • 5,718
  • 5
  • 29
  • 55

1 Answers1

2

Just read the manual: http://php.net/manual/en/language.operators.increment.php

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.

Thomas G
  • 9,886
  • 7
  • 28
  • 41