Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
675 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...