简体   繁体   English

修复 PHP 空函数

[英]Fixing the PHP empty function

PHP has the habit of evaluating (int)0 and (string)"0" as empty when using the empty() function. PHP 在使用empty()函数时有将 (int)0 和 (string)"0" 评估为空的习惯。 This can have unintended results if you expect numerical or string values of 0. How can I "fix" it to only return true to empty objects, arrays, strings, etc?如果您期望数字或字符串值为 0,这可能会产生意外结果。如何“修复”它以仅将 true 返回到空对象、数组、字符串等?

This didn't work for me.这对我不起作用。

if (empty($variable) && '0' != $variable) {
  // Do something
}

I used instead:我改用:

if (empty($variable) && strlen($variable) == 0) {
  // Do something
}

I seldom use empty() for the reason you describe.由于您描述的原因,我很少使用empty() It confuses legitimate values with emptiness.它将合法价值与空虚混为一谈。 Maybe it's because I do a lot of work in SQL, but I prefer to use NULL to denote the absence of a value.也许是因为我在 SQL 中做了很多工作,但我更喜欢使用NULL来表示没有值。

PHP has a function is_null() which tests for a variable or expression being 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";

You can also use the exactly equals operator === to do a similar test:您还可以使用完全等于运算符===进行类似的测试:

if ($foo === null) print "foo is null!\n";

This is true if $foo is NULL , but not if it's false , zero, "" , etc.如果$fooNULL则为真,但如果为false 、零、 ""等则不然。

"0" is always considered false (or empty) in PHP, and it does make alot of sense (not that I'll argue that here). “0”在 PHP 中总是被认为是错误的(或空的),它确实很有意义(我不会在这里争论)。 If you want to have zero evaluate to true as well, use strlen($value) .如果您也想让零评估为真,请使用strlen($value)

I always add to my codebase我总是添加到我的代码库

function is_blank($value) {
    return empty($value) && !is_numeric($value);
}

and use it instead of empty().并使用它代替empty()。 It solves the issue of keeping zeros (int, float or string) as non-empty.它解决了将零(int、float 或 string)保持为非空的问题。

See http://www.php.net/manual/en/function.empty.php#103756 which was added May 2011.请参阅 2011 年 5 月添加的http://www.php.net/manual/en/function.empty.php#103756

"Fixing" is one point of view. “修复”是一种观点。 Another would be to assume it's not "broken", and learn to work with it the way it was intentionally designed.另一种方法是假设它没有“损坏”,并学会按照有意设计的方式使用它。

Given the problem as you describe it, the best thing would be to tighten up your code so the variable can't be put into an indeterminate type state.鉴于您描述的问题,最好的办法是收紧您的代码,这样变量就不能进入不确定的类型状态。 Otherwise, you'll want to test for datatype using gettype().否则,您将需要使用 gettype() 测试数据类型。

Generally speaking you want to use the triple equals operator to determine when a value truly is null or false.一般而言,您希望使用三重等号运算符来确定值何时真正为 null 或 false。 This is more specific and the results ALWAYS return exactly as expected.这是更具体的,结果总是完全按预期返回。

Creating a separate function to do something that you can do in a single line of code but using a different operator seems to be overly complicated and adds additional obfuscation.创建一个单独的函数来完成您可以在一行代码中完成的事情,但使用不同的运算符似乎过于复杂并增加了额外的混淆。

Additionally, many programmers tend to use 0 or an empty string to denote a non-existent value but it is more correct (and I feel a better practice) to use a null value to denote any value (regardless of type) that is truly non-existent.此外,许多程序员倾向于使用 0 或空字符串来表示不存在的值,但使用空值来表示任何真正不存在的值(无论类型如何)更正确(我觉得是一种更好的做法) -存在。

I use this to detect emptiness:我用它来检测空虚:

''  --> true
'0' --> false
0   --> false

the function:功能:

function is_empty_or_zero($str) {
 return (is_null($str) || ($str === ''));
}

You're trying to use empty() for something it's not intended for.您正在尝试将empty()用于它不适合的用途。 Personally, I think it's behaviour comes from an older programming paradigm in PHP and it could probably be retired.就个人而言,我认为它的行为来自 PHP 中较旧的编程范式,它可能会被淘汰。

Instead, make your checks more explicit.相反,让您的检查更加明确。 Rather than checking if the value is not useful, check that it is.与其检查该值是否无用,不如检查它是否有用。 For example, if you want an array, check it's an array ( is_array() ) rather than checking whether it's a string.例如,如果你想要一个数组,检查它是一个数组( is_array() )而不是检查它是否是一个字符串。

Also, you can rely on the fact that all $_POST and $_GET variables are strings, so you can make comparisons to "", or check that strlen() == 0 .此外,您可以依赖所有$_POST$_GET变量都是字符串这一事实,因此您可以与 "" 进行比较,或者检查strlen() == 0

if ( is_int($val) || !empty($val) ) {;}

I used ord function to check either the value passed was empty or not.我使用ord函数来检查传递的值是否为空。

/*
* SPACE is not empty - Please do trim before using this function for your own purpose
*  var_dump(is_having_value(0));        // true
   var_dump(is_having_value(0000));     // true
   var_dump(is_having_value("    0"));  // true
   var_dump(is_having_value(""));       // false
   var_dump(is_having_value("  "));     // true
   var_dump(is_having_value('\t'));     // true
   var_dump(is_having_value(''));       // false
   var_dump(is_having_value('o'));      // true
   var_dump(is_having_value('O'));      // true
   var_dump(is_having_value('0'));      //true
   var_dump(is_having_value(null));     //false
   var_dump(is_having_value());         //false
*/
function is_having_value($val = null) {
    if (is_array($val) || is_object($val)):
        $logic_empty = empty($val);
        return !$logic_empty;
    else:
        $ascii = ord($val);
        if ($ascii == 48 || $ascii = 0 || $ascii == 32):
            return true;
        else:
            $logic_empty = empty($val);
            return !$logic_empty;
        endif;
    endif;
}

I created an IsEmpty() a terse quick function.我创建了一个IsEmpty()一个简洁的快速函数。

function IsEmpty($mData) {
    return is_int($mData) ? false : 
        is_string($mData) ? $mData=="" : 
        empty($mData);
}

If you want an equivalent to empty($var) which returns false when var is the string "0", you can use:如果你想要一个等效于当 var 是字符串“0”时返回 false 的empty($var) ,你可以使用:

if (($var ?? 0) != '')

The reason this works is:这样做的原因是:

  • $var ?? 0 $var ?? 0 is a shortcut for the ternery isset($var) ? $var : 0 $var ?? 0是 ternery isset($var) ? $var : 0的快捷方式isset($var) ? $var : 0 isset($var) ? $var : 0 . isset($var) ? $var : 0 That is, if the variable on the left doesn't exist it takes the value on the right, without issuing a warning or notice, as with isset() or empty().也就是说,如果左边的变量不存在,它会取右边的值,而不发出警告或通知,就像 isset() 或 empty() 一样。

  • <value> != '' does an implicit cast of the empty string when the left value isn't a string. <value> != ''当左值不是字符串时,对空字符串进行隐式转换。 This returns false for any false-like value of <value> such as null, false or (numeric) 0. However, for the string "0", this will return true, since no cast will be performed and "0" != "" is true.对于<value>任何类似 false 的值,例如 null、false 或(数字)0,这将返回 false。但是,对于字符串“0”,这将返回 true,因为将不执行强制转换并且"0" != ""是真的。

The most effective solution for this problem is to test if the variable is false eg这个问题最有效的解决方案是测试变量是否为假,例如


if (!$variable_name) {echo $variable_name;}

It doesn't matter if the variable is empty or null, it all equals to false when put in a if conditional.变量是空还是空都没有关系,当放入 if 条件时,它都等于 false。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM