linpf
V2EX  ›  PHP

php 里, if($foo)跟 if(!empty($foo))是等效的吗?

  •  
  •   linpf · Jun 8, 2015 · 4006 views
    This topic created in 4170 days ago, the information mentioned may be changed or developed.
    如果不等效 在什么地方会有区别?
    9 replies  •  2015-06-09 16:08:56 +08:00
    xuxu
    xuxu
    Jun 8, 2015
    1
    $foo没定义时 if($foo) 会报warning.
    manhere
    manhere
    Jun 8, 2015
    2
    $foo = 0;
    Ison
    Ison
    Jun 8, 2015
    3
    var_dump
    fangjinmin
    fangjinmin
    Jun 8, 2015
    4
    不一样,看函数定义吧。empty对于0, "", 0.0, "0", array(), NULL, FALSE, 没赋值的$var都认为是TRUE.
    oott123
    oott123
    Jun 8, 2015
    5
    > No warning is generated if the variable does not exist. That means empty() is essentially the concise equivalent to !isset($var) || $var == false.
    via http://php.net/manual/en/function.empty.php

    也就是说,在 $var 未定义的时候不等效。
    bombless
    bombless
    Jun 8, 2015
    6
    应该是 if(isset($foo) && $foo)
    wavingclear
    wavingclear
    Jun 9, 2015
    7
    @bombless 1楼是对的
    isset 和 empty 同是语言结构,所以那样写没啥意义……
    cevincheung
    cevincheung
    Jun 9, 2015
    8
    @xuxu notice
    linpf
    linpf
    OP
    Jun 9, 2015
    9
    @manhere 这个情况下不一样
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   721 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 22:43 · PVG 06:43 · LAX 14:43 · JFK 17:43
    ♥ Do have faith in what you're doing.