鍍金池/ 問答/PHP  Python  網(wǎng)絡(luò)安全/ $str1 = "01 "累加的問題

$str1 = "01 "累加的問題

發(fā)現(xiàn)PHP一個很有趣的現(xiàn)象,不知道怎么解釋這種現(xiàn)象。代碼是這樣的:

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

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

為什么說有意思呢,就是$str1都是字符串,但是第一個$str1等于的是"01 "多了一個空格,所以即使用了++,竟然輸出還是本身。按道理,PHP對字符串計算不是會自動轉(zhuǎn)換成數(shù)字(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 字母和數(shù)字 (a-z、a-z 和 0-9)。(另外注意這段中文文檔和英文的對不上,暫且以英文為準(zhǔn))

  3. 可參考這篇
2017年3月11日 18:51