A classmate asked a question:
Copy the code The code is as follows:
for($i = 'A'; $i <= 'Z'; $i++) {
echo $i;
}
What is the output?
The output is:
ABCDEFGHIJKLMNOPQRSTUVWXYZAAABACADAEAFAGAHAIAJAKALAMANAOAPAQARAS….
Why?
It’s actually very simple, and there are instructions in the PHP manual, but I’m afraid many people don’t understand it chapter by chapter. Read the manual carefully:
PHP follows Perl's convention when dealing with arithmetic operations on character variables and not C's. For example, in Perl 'Z'+1 turns into 'AA', while in C 'Z'+1 turns into '[ ' ( ord('Z') == 90, ord('[') == 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.
In When dealing with arithmetic operations on character variables, PHP follows Perl's habits rather than C's. For example, in Perl 'Z'+1 will get 'AA', while in C, 'Z'+1 will get '[' (ord('Z') == 90, ord('[') == 91). Note that character variables can only be incremented, not decremented, and only pure letters (a-z and A-Z) are supported.
That is, if:
Copy the code The code is as follows:
$name = "laruence";
++$name; //will be "laruencf"
And:
Copy the code The code is as follows:
$name = "laruence";
--$name; //No effect, still "laruence"
So, the cause of this problem is when $i = Z , ++$i becomes AA, and when comparing strings,
AA, BB, XX to YZ are all less than or equal to Z... so..
The above introduces the analysis of string constants in PHP's incremental operation on strings, including the content of string constants. I hope it will be helpful to friends who are interested in PHP tutorials.