有人能解释一下 PHP 将空数组与任意数字进行比较并返回 true
时会发生什么吗?
var_dump([] > -1); // true
var_dump([] > 0); // true
var_dump([] > 222222222) // true
我在 PHP 7.0、7.1 和 5.6 中对此进行了测试。
最佳答案
首先,请不要进行这种比较;执行此操作的代码非常可疑,并且可能非常损坏。
回答你的问题:原因是数组与非数组的比较具有定义的行为 set out in the documentation 。该数组始终大于与其比较的任何标量值。对象总是大于数组,数组总是大于标量(例如整数)。其他比较可以通过多种方式处理,如文档中所定义。
来自文档:
Comparison with Various Types
Type of Operand 1 Type of Operand 2 Result ... array anything array is always greater
一些示例代码和 demo :
var_dump(
[] > -1, //true
[] > 0, // true
[] > 222222222, // true
[] > [], // false, obviously
[] > new stdClass(), //false, object wins
new stdClass() > [] // true, object wins
);
关于php - 为什么空数组比任何数字都大?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41146862/