Clément Baconnier
Clément Baconnier

Reputation: 6058

In PHP why does range a-Z and a for loop applied to the alphabet produce different characters?

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?

Upvotes: 1

Views: 236

Answers (1)

Thomas G
Thomas G

Reputation: 10216

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.

Upvotes: 2

Related Questions