【问题标题】:PHP type juggling and decrement operatorPHP 类型杂耍和减量运算符
【发布时间】:2015-11-19 06:50:06
【问题描述】:

我正在使用 PHP 中的 for-loop 和 CLI。我遇到了递减运算符(--)的问题。下面是我的代码,

<?php

    $handle = fopen("php://stdin","r");
    $str = fgets($handle);
    for($i=$str; $i>0; $i--){   
        var_dump($i);
    }

对于任何大于 0 的数字,它都会进入无限循环。下面是输出,

john@doe:/var/www/html/rank$ php 1.php
3
string(2) "3
"
string(2) "3
"
string(2) "3
"
string(2) "3
"
string(2) "3
"
string(2) "3
"

但如果我将强制转换 cli 参数显式键入 int,它会起作用,

<?php

    $handle = fopen("php://stdin","r");
    $str = (int)fgets($handle);
    for($i=$str; $i>0; $i--){   
        var_dump($i);
    }

输出

john@doe:/var/www/html/rank$ php 1.php
3
int(3)
int(2)
int(1)
john@doe:/var/www/html/rank$

是我做错了什么还是类型杂耍不适用于减量运算符(故意)?因为它似乎可以与下面的增量运算符(++)一起使用

<?php

    $handle = fopen("php://stdin","r");
    $str = fgets($handle);
    for($i="1"; $i<=$str; $i++){    
        var_dump($i);
    }

输出

john@doe:/var/www/html/rank$ php 1.php
3
string(1) "1"
int(2)
int(3)
john@doe:/var/www/html/rank$

【问题讨论】:

    标签: php type-conversion decrement


    【解决方案1】:

    您从文件中获取的$str 中有一个换行符:

    string(2) "3
    "
    

    所以字符串的 ascii 字符是 #51(字符“3”的十进制 ASCII 代码)和#10(换行的十进制 ASCII 代码)。 如果您使用递减运算符i--,则字符串将更改为#51#09。下一次迭代会将其更改为#51#08。

    第一个字符不会改变,因为第二个字符会递减。这就是为什么看起来没有递减的原因。

    解决方案:

    如果你改变了

    $str = fgets($handle);
    

    到

    $str = trim(fgets($handle));
    

    换行符,制表符等将被删除,减量运算符将减少字符#51。

    【讨论】:

      猜你喜欢
      • 2012-02-22
      • 2011-08-29
      • 2012-10-04
      • 2013-03-26
      • 2016-10-27
      • 1970-01-01
      • 1970-01-01
      • 2020-09-29
      • 1970-01-01
      相关资源
      最近更新 更多