$str1 = "01 "累加的问题

发现PHP一个很有趣的现象,不知道怎么解释这种现象。代码是这样的:

    $str1 = "01 ";
    $str1++;
    echo $str1;//得到01

    $str1 = "01";
    $str1++;
    echo $str1;//得到2

为什么说有意思呢,就是$str1都是字符串,但是第一个$str1等于的是"01 "多了一个空格,所以即使用了++,竟然输出还是本身。按道理,PHP对字符串计算不是会自动转换成数字(1)来强制累增吗,怎么因为包含有个空格就不计算了?
郁闷,求解释。谢谢了

阅读 2.4k
1 个回答
  1. 我觉得这样写会清楚一些:

    <?php
    $str1 = "01 ";
    $str1++;
    var_export($str1);//得到'01 '
    
    $str2 = "01";
    $str2++;
    var_export($str2);//得到2
  2. 参见这里的解释:

    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.

    大意是说,使用自增/自减操作字符串时,可以递增但不能递减,另外只支持(字符串的末位为)纯 ASCII 字母和数字 (a-z、a-z 和 0-9)。(另外注意这段中文文档和英文的对不上,暂且以英文为准)

  3. 可参考这篇
推荐问题
宣传栏