Watch following code:
$a = 'Test';
echo ++$a;
This will output:
Tesu
Question is, why ?
I know "u" is after "t", but why it doesn’t print "1" ???
PHP Documentation:
Also, the variable being incremented
or decremented will be converted to
the appropriate numeric data
type—thus, the following code will
return 1, because the string Test is
first converted to the integer number
0, and then incremented.
In PHP you can increment strings (but you cannot “increase” strings using the addition operator, since the addition operator will cause a string to be cast to an
int, you can only use the increment operator to “increase” strings!… see the last example):So
"a" + 1is"b"after"z"comes"aa"and so on.So after
"Test"comes"Tesu"You have to watch out for the above when making use of PHP’s automatic type coercion.
Automatic type coercion:
No automatic type coercion! (incrementing a string):
You have to do some extra work if you want to deal with the ASCII ordinals of letters.
If you want to convert letters to their ASCII ordinals use ord(), but this will only work on one letter at a time.
live example
The above makes use of the fact that strings can only be incremented in PHP. They cannot be increased using the addition operator. Using an addition operator on a string will cause it to be cast to an
int, so:Strings cannot be “increased” using the addition operator:
The above will try to cast “
Test” to an(int)before adding1. Casting “Test” to an(int)results in0.Note: You cannot decrement strings:
The previous means that
echo --$a;will actually printTestwithout changing the string at all.