Home >Backend Development >PHP Tutorial >Detailed analysis of PHP's incremental operation on strings

Detailed analysis of PHP's incremental operation on strings

怪我咯
怪我咯Original
2017-07-04 15:01:381423browse

When dealing with arithmetic operations on characters variables, PHP follows Perl's habits instead of C's.

A classmate asked a question:

Copy code The code is as follows:

<?php 
for($i = &#39;A&#39;; $i <= &#39;Z&#39;; $i++) { 
echo $i; 
}

What is the output?

The output is:

ABCDEFGHIJKLMNOPQRSTUVWXYZAAABACADAEAFAGAHAIAJAKALAMANAOAPAQARAS…….

Why?

It’s actually very simple. There are also instructions in the PHP manual, but I’m afraid many people don’t know how to follow each chapter. Please 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.

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.

In other words, if:

the code is as follows:

$name = "laruence"; 
++$name; //将会是"laruencf"

and:

the code is as follows:

$name = "laruence"; 
--$name; //没有影响, 还是"laruence"

So, the reason for this problem is that when $i = Z, ++$i becomes AA, and when comparing strings ,
AA, BB, XX all the way to YZ Less than or equal to Z... so..

The above is the detailed content of Detailed analysis of PHP's incremental operation on strings. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn