yazi
V2EX  ›  PHP

PHP 中,为何 [] > n == true ?

  •  
  •   yazi · Jan 10, 2019 · 4752 views
  •   You need to sign in to view this topic
    This topic created in 2831 days ago, the information mentioned may be changed or developed.

    今天无意间遇到的问题,拿一个数组和任何数字大于比较都是 true,小于比较都是 false (目前测试是这样)。

    查了 PHP 数组操作符,发现只有 + == != 等这些,并没有 < 或 > 。

    http://php.net/manual/zh/language.operators.array.php

    Google 也查了,没有发现有价值的信息(也可能是我查询姿势不对),所以来请教下各位 V 油为何会有这样的结果?


    我测试的 PHP 版本有 PHP 5.6.36 、PHP 7.2.10

    10 replies  •  2019-01-10 14:54:03 +08:00
    xnode
        1
    xnode  
       Jan 10, 2019
    好像是 把数组转成 string n 也转换成 string 然后再比较
    WuwuGin
        2
    WuwuGin  
       Jan 10, 2019   ❤️ 1
    $a <> $b Inequality TRUE if $a is not equal to $b.
    https://secure.php.net/manual/en/language.operators.array.php
    Fuor
        3
    Fuor  
       Jan 10, 2019   ❤️ 2
    http://php.net/manual/zh/language.operators.comparison.php

    array 和任何其它类型比较,array 总是更大
    liuguang
        4
    liuguang  
       Jan 10, 2019
    这样搞有意义吗?无非就是数据转换,谁先谁后的问题,根本用不到这种代码
    orqzsf1
        5
    orqzsf1  
       Jan 10, 2019
    couashi
        6
    couashi  
       Jan 10, 2019   ❤️ 1
    真的无聊
    KomeijiSatori
        7
    KomeijiSatori  
       Jan 10, 2019
    为啥要用数组和数字比较呢(
    yazi
        8
    yazi  
    OP
       Jan 10, 2019
    @liuguang 对的,这样是没意义的,正因为没意义所以平常也不会这么写。今天偶然这么写了句发现返回的是 true,觉得有意思就查了下(
    solu
        9
    solu  
       Jan 10, 2019
    先不管什么时候会这么用, 由于感兴趣翻了一下源码,我来尝试解答一下吧。

    [] > 整型

    前略,这两个类型比较最终调用了函数 is_smaller_function ( https://github.com/php/php-src/blob/54dc07f3dc9fa2fcfeb2d2c6aebf79bd34ab041c/Zend/zend_operators.c#L2243)

    然后调用的是 compare_function,这里的 op1 是整型 IS_LONG,op2 是数组 IS_ARRAY ;
    接着这函数前面一大堆代码不用看了到 +2146 行
    else if (Z_TYPE_P(op2)==IS_ARRAY) {
    ZVAL_LONG(result, -1);
    return SUCCESS;
    }
    直接返回了-1

    ZVAL_BOOL(result, (Z_LVAL_P(result) < 0));

    到这里 -1 < 0 所以比较的结果就为 true 了。

    PS:我本地版本的源码 op2 == IS_OBJECT 也会返回 -1,但是 GitHub 上的版本已经删除了这个判断
    solu
        10
    solu  
       Jan 10, 2019
    这排版。。。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2578 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 49ms · UTC 16:08 · PVG 00:08 · LAX 09:08 · JFK 12:08
    ♥ Do have faith in what you're doing.