为什么空数组大于任何数字? [英] Why is an empty array greater than any number?

查看:64
本文介绍了为什么空数组大于任何数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释一下PHP比较任何数字的空数组并返回 true 的情况吗?

Could someone explain what happens under the hood in PHP when it compares an empty array with any number and returns true?

var_dump([] > -1); // true
var_dump([] > 0); // true
var_dump([] > 222222222) // true

我对此进行了测试在PHP 7.0、7.1和5.6中。

I tested this in PHP 7.0, 7.1 and 5.6.

推荐答案

首先,请不要进行这种比较;

First of all, please never do this kind of comparison; code that does this is highly suspect and probably very broken.

要回答您的问题:原因是,将数组与非数组进行比较时,行为定义为 。数组始终大于要与之进行比较的任何标量值。对象总是大于数组,并且数组总是大于标量(例如整数)。其他比较方法按照文档中定义的多种方式进行处理。

To answer your question: the reason is that comparison of an array to a non-array has a defined behavior as set out in the documentation. The array is always greater than any scalar value to which it is compared. Objects are always greater than arrays, and arrays are always greater than scalars (such as integers). Other comparisons are handled in a variety of ways, as defined in the docs.

从文档中:


比较


Type of Operand 1    Type of Operand 2    Result
...
array                anything             array is always greater


一些示例代码和演示

var_dump(
    [] > -1, //true
    [] > 0, // true
    [] > 222222222, // true
    [] > [], // false, obviously
    [] > new stdClass(), //false, object wins
    new stdClass() > [] // true, object wins
    );

这篇关于为什么空数组大于任何数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆