小智 37
这不适合我.
if (empty($variable) && '0' != $variable) {
// Do something
}
Run Code Online (Sandbox Code Playgroud)
我改为使用:
if (empty($variable) && strlen($variable) == 0) {
// Do something
}
Run Code Online (Sandbox Code Playgroud)
Bil*_*win 19
我很少使用empty()你描述的原因.它将合法价值与空虚混为一谈.也许是因为我在SQL中做了很多工作,但我更喜欢NULL用来表示没有值.
PHP有一个is_null()测试变量或表达式的函数NULL.
$foo = 0;
if (is_null($foo)) print "integer 0 is null!\n";
else print "integer 0 foo is not null!\n";
$foo = "0";
if (is_null($foo)) print "string '0' is null!\n";
else print "string '0' is not null!\n";
$foo = "";
if (is_null($foo)) print "string '' is null!\n";
else print "string '' is not null!\n";
$foo = false;
if (is_null($foo)) print "boolean false is null!\n";
else print "boolean false is not null!\n";
Run Code Online (Sandbox Code Playgroud)
您还可以使用完全相等的运算符===来执行类似的测试:
if ($foo === null) print "foo is null!\n";
Run Code Online (Sandbox Code Playgroud)
如果$foo是NULL,则为真,但如果是,则false为零"",等等.
我总是添加到我的代码库
function is_blank($value) {
return empty($value) && !is_numeric($value);
}
Run Code Online (Sandbox Code Playgroud)
并使用它代替empty()。它解决了将零(int、float 或 string)保持为非空的问题。
请参阅2011 年 5 月添加的http://www.php.net/manual/en/function.empty.php#103756。