记PHP比较运算符的一个用例

最近被问到如下的一道题:

$x = false;
$i = 9;
for ($i = 9; $i > $x; $i -= 2) {
    echo $i . "\n";
}
//请说出代码执行后的输出结果。

一般想到int类型$i和bool类型的$x比较,bool类型的false会被转换成int类型的0,所以代码块会有5次输出后停止结束。

那么实际执行结果是怎样的呢?

实际执行一次,就会发现,结果是无限循环输出:9,7,5,3,1,-1,-3,-5,……。

为什么呢?

仔细查看PHP文档:https://www.php.net/manual/en/language.operators.comparison.php

会发现有这样的描述:

Type of Operand 1 Type of Operand 2 Result
null or string string Convert null to “”, numerical or lexical comparison
bool or null anything Convert both sides to boolfalse < true
object object Built-in classes can define its own comparison, different classes are uncomparable, same class see Object Comparison
stringresourceint or float stringresourceint or float Translate strings and resources to numbers, usual math
array array Array with fewer members is smaller, if key from operand 1 is not found in operand 2 then arrays are uncomparable, otherwise – compare value by value (see following example)
object anything object is always greater
array anything array is always greater

其中第二行就有关于bool类型和其他类型的比较,有明确说明,会把其他类型转换成bool类型。那么上文中的这道题,$i总是不等于0,即意味着$i总是会被转换成bool类型的true,true永远大于false,所以会有无限循环的输出。

 

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

*