PHP 类型杂耍和递减运算符
PHP type juggling and decrement operator
我正在玩 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$
您从文件中获取的 $str
中有一个换行符:
string(2) "3
"
所以字符串的ascii字符是#51
(字符“3”的十进制ASCII码)和#10
(换行符的十进制ASCII码)。
如果您使用递减运算符 i--
,则字符串将更改为 #51#09
。下一次迭代会将其更改为 #51#08
.
第一个字符不会改变,因为第二个字符会递减。这就是为什么看起来没有递减的原因。
解法:
如果你改变
$str = fgets($handle);
到
$str = trim(fgets($handle));
换行符、制表符等将被删除,以便递减运算符将递减字符 #51
。
我正在玩 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$
您从文件中获取的 $str
中有一个换行符:
string(2) "3
"
所以字符串的ascii字符是#51
(字符“3”的十进制ASCII码)和#10
(换行符的十进制ASCII码)。
如果您使用递减运算符 i--
,则字符串将更改为 #51#09
。下一次迭代会将其更改为 #51#08
.
第一个字符不会改变,因为第二个字符会递减。这就是为什么看起来没有递减的原因。
解法:
如果你改变
$str = fgets($handle);
到
$str = trim(fgets($handle));
换行符、制表符等将被删除,以便递减运算符将递减字符 #51
。