Php implements a to z and its "strange phenomenon"

Source: Internet
Author: User

Version 1:
For ($ I = ord ('A'); $ I <ord ('Z'); $ I ++ ){
Echo chr ($ I );
}

Version 2 (similar to the first version using ascii ):
For ($ I = 0; $ I <26; $ I ++ ){
Echo chr ($ I + 97 );
}
Version 3:
Echo implode ('', range ('A', 'z '));
Version 4 ):
For ($ I = 'a'; $ I! = 'A'; $ I ++ ){
Echo $ I;
}
Version 5:
For ($ I = 'a'; strlen ($ I) <2; $ I ++ ){
Echo $ I;
}
The first two cycles are easy to understand. The ascii values of each letter from a to z are incremental, so the two methods use the ascii values for cyclic calculation, php built-in ord () and chr () functions are used.
The third method uses the range () function built in php to generate an array that increments from a to z. The step size is 1, and then the implode function is used to merge the array into a string.
The last two methods are the "strange phenomenon" mentioned in the title of this article ".
In theory, we use the for ($ I = 'a'; $ I <'Z'; $ I ++) method is also very correct and reasonable... But the reality is cruel. If you try it, you will find that you don't want the result. A to z is before, and a long string of characters is output later.
If you output a line feed in the for loop and observe it again, you will find a rule, a-z. The next output is aa, AB, ac... az, then ba, bb, bc... bz .... that is, php automatically "carry" after adding one to z. Php a strange 26 hexadecimal. After adding 1 to the z of "current bit", 1 is added to the first bit before it, and the current bit is changed to. 'Z' ++ => 'A', 'az' => 'ba', 'zz '=> 'AAA '....
Note: 1. This rule cannot be used for judgment. For example, 'Z' <'AA' is false. In php, strings are compared from left to right. 2. Currently, this rule is only found when "pre-auto-increment" or "pre-auto-subtraction" occurs. During other arithmetic operations, php converts the pure string to 0.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.