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

Categories

$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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...