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

Detailed analysis of PHP's incremental operation on strings

怪我咯
Release: 2023-03-12 16:32:01
Original
1422 people have browsed it

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; 
}
Copy after login

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"
Copy after login

and:

the code is as follows:

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

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template