Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment character works but adding doesn't. Why?

Tags:

php

$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?

like image 528
Shubham Avatar asked May 06 '12 08:05

Shubham


People also ask

How do you increment a character?

There is another way to increment a character using bytes. Convert str into bytes. The result will an array containing ASCII values of all characters of a string. Adding 1 to the first char of converted bytes.


3 Answers

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
like image 125
ThiefMaster Avatar answered Oct 17 '22 16:10

ThiefMaster


The reason is PHP treating variables in a context specific way. It's a bit similar to Visual Basic.

The expression 'a' + 1 uses mathematical addition. In this context a is interpreted as a number, so it will be considered 0 (if you're familiar with C, it's like feeding the string "a" into atoi()).

If you'd use the expression 'a' . 1 the result would be a1 due to it using string concatenation.

To get the result you expected (b), you'd have to use chr(ord('a') + 1), where ord() explicitly returns the ASCII value of the (first) character.

$a++ is a special case, essentially an overload looking at the ascii value instead of the value itself as the variable.

like image 20
Mario Avatar answered Oct 17 '22 16:10

Mario


From http://php.net/manual/en/types.comparisons.php, "a"+1 is executed as 0+1. Where some languages (C#) will translate (string)+(int) to (string)+(string), PHP does the opposite: (int)+(int).

To force string concatenation instead: "a" . 1 yields 'a1'.

like image 1
Cory Carson Avatar answered Oct 17 '22 14:10

Cory Carson