Increment behavior on strings - PHP easter egg?

耗尽温柔 提交于 2019-11-27 07:49:10

问题


$var = 'test_1';
var_dump(++$var); // string(6) "test_2" 

$var2 = '1_test';
var_dump(++$var2); // string(6) "1_tesu"

$var3 = 'test_z';
var_dump(++$var3); // string(6) "test_a"

$var4 = 'test_';
var_dump(++$var4); // string(5) "test_"

So apparently, using an increment operator on a string has the effect of increasing the digit if the last character is a number, increasing the letter and then resetting to a once z if the last character is in the alphabet, and has no effect on non alpha numeric characters.

Is this a standard feature, expected in many scripting languages, or did I just find a PHP easter egg?


回答1:


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 characters (a-z and A-Z) are supported. Incrementing/decrementing other character variables has no effect, the original string is unchanged.

-> http://php.net/manual/en/language.operators.increment.php




回答2:


Its officially documentated http://php.net/language.operators.increment




回答3:


It's not an Easter egg. It's expected in PHP, but no it's not common in other languages. (At least not incrementing letters.) PHP treats strings containing a number the same as numbers in most cases. So you can also "2" * "2" for example.



来源:https://stackoverflow.com/questions/8885440/increment-behavior-on-strings-php-easter-egg

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!