Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
626 views
in Technique[技术] by (71.8m points)

php - Increment character works but adding doesn't. Why?

$a = 'a';
print ($a+1);
print ($a++);
print $a;

The output is: 1 a b

So it is clear that increment operator did its job but I don't understand why output is '1' in case $a+1. Can anyone explain?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

PHP is not C, so 'a' + 1 is not 'b'.

'a' in a numeric context is 0, and 0+1 = 1.

php> echo (int)'a';
0

The fact that the postfix/prefix increment operators do work like if it was a C char seems to be a nasty "feature" of PHP. Especially since the decrement operators are a no-op in this case.

When you increment 'z' it gets even worse:

php> $a = 'z';
php> echo ++$a
aa

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...