$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?
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.
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
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.
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'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With