简体   繁体   English

检查变量是否为空或空字符串的更好方法?

[英]Better way to check variable for null or empty string?

Since PHP is a dynamic language what's the best way of checking to see if a provided field is empty? 由于PHP是一种动态语言,检查提供的字段是否为空的最佳方法是什么?

I want to ensure that: 我想确保:

  1. null is considered an empty string null被视为空字符串
  2. a white space only string is considered empty 仅限空白字符串被视为空
  3. that "0" is not considered empty “0”不算空

This is what I've got so far: 这是我到目前为止所得到的:

$question = trim($_POST['question']);

if ("" === "$question") {
    // Handle error here
}

There must be a simpler way of doing this? 必须有一种更简单的方法吗?

// Function for basic field validation (present and neither empty nor only white space
function IsNullOrEmptyString($str){
    return (!isset($str) || trim($str) === '');
}

Old post but someone might need it as I did ;) 老帖子,但有人可能需要它,因为我做;)

if (strlen($str) == 0){
do what ever
}

replace $str with your variable. 用你的变量替换$str NULL and "" both return 0 when using strlen . 使用strlen时, NULL""都返回0。

Use PHP's empty() function. 使用PHP的empty()函数。 The following things are considered to be empty 以下事项被认为是空的

"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)

For more details check empty function 有关详细信息,请检查空功能

I'll humbly accept if I'm wrong, but I tested on my own end and found that the following works for testing both string(0) "" and NULL valued variables: 如果我错了,我会谦卑地接受,但我在自己的测试结果中发现以下内容适用于测试字符串(0)“”和NULL值变量:

if ( $question ) {
  // Handle success here
}

Which could also be reversed to test for success as such: 这也可以反过来测试成功如下:

if ( !$question ) {
  // Handle error here
}

Beware false negatives from the trim() function — it performs a cast-to-string before trimming, and thus will return eg "Array" if you pass it an empty array. 注意trim()函数的错误否定 - 它在修剪之前执行强制转换,因此如果你传递一个空数组,它将返回例如“Array”。 That may not be an issue, depending on how you process your data, but with the code you supply, a field named question[] could be supplied in the POST data and appear to be a non-empty string. 这可能不是问题,取决于您处理数据的方式,但是使用您提供的代码,可以在POST数据中提供名为question[]的字段,并且该字段看起来是非空字符串。 Instead, I would suggest: 相反,我会建议:

$question = $_POST['question'];

if (!is_string || ($question = trim($question))) {
    // Handle error here
}

// If $question was a string, it will have been trimmed by this point

There is no better way but since it's an operation you usually do quite often, you'd better automatize the process. 没有更好的方法,但由于这是一项经常做的操作,你最好自动化这个过程。

Most frameworks offer a way to make arguments parsing an easy task. 大多数框架提供了一种使参数解析为简单任务的方法。 You can build you own object for that. 您可以为此构建自己的对象。 Quick and dirty example : 快速而肮脏的例子:

class Request
{

    // This is the spirit but you may want to make that cleaner :-)
    function get($key, $default=null, $from=null)
    {
         if ($from) :
             if (isset(${'_'.$from}[$key]));
                return sanitize(${'_'.strtoupper($from)}[$key]); // didn't test that but it should work
         else
             if isset($_REQUEST[$key])
                return sanitize($_REQUEST[$key]);

         return $default;
    }

    // basics. Enforce it with filters according to your needs
    function sanitize($data)
    {
          return addslashes(trim($data));
    }

    // your rules here
    function isEmptyString($data)
    {
        return (trim($data) === "" or $data === null);
    }


    function exists($key) {}

    function setFlash($name, $value) {}

    [...]

}

$request = new Request();
$question= $request->get('question', '', 'post');
print $request->isEmptyString($question);

Symfony use that kind of sugar massively. Symfony大量使用那种糖。

But you are talking about more than that, with your "// Handle error here ". 但是你在谈论的不仅仅是“你在这里处理错误”。 You are mixing 2 jobs : getting the data and processing it. 您正在混合两个工作:获取数据并进行处理。 This is not the same at all. 这根本不一样。

There are other mechanisms you can use to validate data. 您可以使用其他机制来验证数据。 Again, frameworks can show you best pratices. 同样,框架可以向您展示最佳实践。

Create objects that represent the data of your form, then attach processses and fall back to it. 创建表示表单数据的对象,然后附加进程并回退到它。 It sounds far more work that hacking a quick PHP script (and it is the first time), but it's reusable, flexible, and much less error prone since form validation with usual PHP tends to quickly become spaguetti code. 听起来更快的PHP脚本(这是第一次)听起来更多的工作,但它是可重用的,灵活的,并且更不容易出错,因为使用通常的PHP进行表单验证会很快变成spaguetti代码。

to be more robust (tabulation, return…), I define: 为了更健壮(制表,返回...),我定义:

function is_not_empty_string($str) {
    if (is_string($str) && trim($str, " \t\n\r\0") !== '')
        return true;
    else
        return false;
}

// code to test
$values = array(false, true, null, 'abc', '23', 23, '23.5', 23.5, '', ' ', '0', 0);
foreach ($values as $value) {
    var_export($value);
    if (is_not_empty_string($value)) 
        print(" is a none empty string!\n");
    else
        print(" is not a string or is an empty string\n");
}

sources: 来源:

When you want to check if a value is provided for a field, that field may be a string , an array , or undifined. 如果要检查是否为字段提供了值,则该字段可以是stringarray或未定义的。 So, the following is enough 所以,以下就足够了

function isSet($param)
{
    return (is_array($param) && count($param)) || trim($param) !== '';
}

This one checks arrays and strings: 这个检查数组字符串:

function is_set($val) {
  if(is_array($val)) return !empty($val);

  return strlen(trim($val)) ? true : false;
}

empty() used to work for this, but the behavior of empty() has changed several times. empty()曾经为此工作,但empty()的行为已经多次改变。 As always, the php docs are always the best source for exact behavior and the comments on those pages usually provide a good history of the changes over time. 与往常一样,php文档始终是确切行为的最佳来源,这些页面上的注释通常提供了随时间变化的良好历史记录。 If you want to check for a lack of object properties, a very defensive method at the moment is: 如果你想检查缺少对象属性,目前一种非常防御的方法是:

if (is_object($theObject) && (count(get_object_vars($theObject)) > 0)) {

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

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