V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
linpf
V2EX  ›  PHP

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

  •  
  •   linpf · 2015-06-08 16:48:30 +08:00 · 3038 次点击
    这是一个创建于 3216 天前的主题,其中的信息可能已经有所发展或是发生改变。
    如果不等效 在什么地方会有区别?
    9 条回复    2015-06-09 16:08:56 +08:00
    xuxu
        1
    xuxu  
       2015-06-08 16:51:32 +08:00
    $foo没定义时 if($foo) 会报warning.
    manhere
        2
    manhere  
       2015-06-08 16:54:06 +08:00
    $foo = 0;
    Ison
        3
    Ison  
       2015-06-08 17:34:41 +08:00
    var_dump
    fangjinmin
        4
    fangjinmin  
       2015-06-08 18:04:56 +08:00
    不一样,看函数定义吧。empty对于0, "", 0.0, "0", array(), NULL, FALSE, 没赋值的$var都认为是TRUE.
    oott123
        5
    oott123  
       2015-06-08 18:47:49 +08:00
    > 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
        6
    bombless  
       2015-06-08 19:33:30 +08:00
    应该是 if(isset($foo) && $foo)
    wavingclear
        7
    wavingclear  
       2015-06-09 00:34:14 +08:00
    @bombless 1楼是对的
    isset 和 empty 同是语言结构,所以那样写没啥意义……
    cevincheung
        8
    cevincheung  
       2015-06-09 11:53:28 +08:00
    @xuxu notice
    linpf
        9
    linpf  
    OP
       2015-06-09 16:08:56 +08:00
    @manhere 这个情况下不一样
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4511 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 10:07 · PVG 18:07 · LAX 03:07 · JFK 06:07
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.