简体   繁体   中英

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 'az' instead of using the ASCII table?

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

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 (az, AZ and 0-9) are supported. Incrementing/decrementing other character variables has no effect, the original string is unchanged.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM