PHP's analysis of string increments
- 2020-03-31 21:07:28
- OfStack
Some students asked a question:
What is the output?
The output is:
ABCDEFGHIJKLMNOPQRSTUVWXYZAAABACADAEAFAGAHAIAJAKALAMANAOAPAQARAS... .
Why?
It's actually quite simple. There are instructions in the PHP manual, but I'm afraid that many people will not read the manual carefully chapter by chapter:
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, Word ('/') = = 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.
When it comes to arithmetic on character variables, PHP follows Perl's conventions, not C's. For example, in Perl 'Z'+1 will get 'AA', while in C 'Z'+1 will get' [' (ord('Z') == 90, ord(' [') == 91).
That is, if:
And:
So, the reason for this problem is that when $I = Z, ++$I becomes AA, and when strings are compared,
AA,BB,XX up to YZ are all less than or equal to Z... So..
<?php
for($i = 'A'; $i <= 'Z'; $i++) {
echo $i;
}
What is the output?
The output is:
ABCDEFGHIJKLMNOPQRSTUVWXYZAAABACADAEAFAGAHAIAJAKALAMANAOAPAQARAS... .
Why?
It's actually quite simple. There are instructions in the PHP manual, but I'm afraid that many people will not read the manual carefully chapter by chapter:
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, Word ('/') = = 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.
When it comes to arithmetic on character variables, PHP follows Perl's conventions, not C's. For example, in Perl 'Z'+1 will get 'AA', while in C 'Z'+1 will get' [' (ord('Z') == 90, ord(' [') == 91).
That is, if:
$name = "laruence";
++$name; //Will be "laruencf"
And:
$name = "laruence";
--$name; //It doesn't matter. It's still "laruence."
So, the reason for this problem is that when $I = Z, ++$I becomes AA, and when strings are compared,
AA,BB,XX up to YZ are all less than or equal to Z... So..