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

2015-06-08 16:48:30 +08:00
 linpf
如果不等效 在什么地方会有区别?
3053 次点击
所在节点    PHP
9 条回复
xuxu
2015-06-08 16:51:32 +08:00
$foo没定义时 if($foo) 会报warning.
manhere
2015-06-08 16:54:06 +08:00
$foo = 0;
Ison
2015-06-08 17:34:41 +08:00
var_dump
fangjinmin
2015-06-08 18:04:56 +08:00
不一样,看函数定义吧。empty对于0, "", 0.0, "0", array(), NULL, FALSE, 没赋值的$var都认为是TRUE.
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
2015-06-08 19:33:30 +08:00
应该是 if(isset($foo) && $foo)
wavingclear
2015-06-09 00:34:14 +08:00
@bombless 1楼是对的
isset 和 empty 同是语言结构,所以那样写没啥意义……
cevincheung
2015-06-09 11:53:28 +08:00
@xuxu notice
linpf
2015-06-09 16:08:56 +08:00
@manhere 这个情况下不一样

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/196969

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX