修复PHP空函数

nul*_*ull 28 php function object

当使用该empty()函数时,PHP习惯于将(int)0和(string)"0"评估为空.如果你期望数值或字符串值为0,这可能会产生意想不到的结果.如何"修复"它只返回空对象,数组,字符串等?

小智 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)

  • 第一个失败是因为你使用`!=`而不是`!==`.`(空($ variable)&& $ variable!=='0')`实际上是一种测试它的简洁方法. (5认同)

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)

如果$fooNULL,则为真,但如果是,则false为零"",等等.


too*_*php 7

在PHP中,"0" 总是被认为是假(或空),它确实有很多意义(不是我会在这里争论).如果您想将零评估为true,请使用strlen($value).


Ste*_*mar 6

我总是添加到我的代码库

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