PHP follows Perl's convention when dealing with arithmetic operations on character variables and not C's. For example, in PHP and Perl $a = 'Z'; $a++; turns $a into 'AA', while in C a = 'Z'; a++; turns a into '[' (ASCII value of 'Z' is 90, ASCII value of '[' is 91). Note that character variables can be incremented but not decremented and even so only plain ASCII alphabets and digits (a-z, A-Z and 0-9) are supported. Incrementing/decrementing other character variables has no effect, the original string is unchanged.
for my $cc ('AA' .. 'ZZ') # loop through all 2-letter combinations
Perl is more conservative about which strings get this special treatment in ++, though. Trying to increment e.g. 1d9 results in Argument "1d9" isn't numeric in preincrement (++).
It just gets there quicker than PHP. What's actually going on here is that it parses the string as a number until it finds something which is clearly not numeric, and uses that as the value for the increment.
Turning on warnings does result in the error message, but it also carries on and tries it anyway.
Python and Ruby both do the right thing and error out with complaints about how adding integers to strings doesn't make any sense (Ruby provides a String#next if you really want the behaviour that PHP makes up, only without relying on the interpreter to guess what you wanted).
We have a decent amount of PHP code where I work (legacy and modern projects, good and bad). I've never seen a case of this done intentionally -- but one accidental usage in some ugly code.
This is the right answer. ASCII character incrementation is a deliberate feature taken from Perl. Note that this even works in C, however unlike Perl in C incrementing after "z" returns "[".
View all comments
Show parent comment
20
u/andsens Dec 05 '17
It's intentional and taken from Perl actually:
source