既然PHP是一种动态语言,那么检查所提供字段是否为空的最佳方法是什么?

我要确保:

Null被认为是空字符串 只有空格的字符串被认为是空的 那个“0”不是空的

这是我目前得到的:

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

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

一定有更简单的方法吧?


当前回答

小心来自trim()函数的错误否定——它在修剪之前执行强制转换为字符串,因此将返回例如。数组,如果你传递给它一个空数组。这可能不是问题,这取决于您如何处理数据,但是对于您提供的代码,可以在POST数据中提供一个名为question[]的字段,并且看起来是非空字符串。相反,我建议:

$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

其他回答

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

使用PHP的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)

有关详细信息,请检查空函数

旧帖子,但有人可能会像我一样需要它;)

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

用变量替换$str。 NULL和""在使用strlen时都返回0。

这个检查数组和字符串:

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

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

为了更健壮(制表,返回…),我定义:

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");
}

来源:

https://www.php.net/manual/en/function.is-string.php https://www.php.net/manual/en/function.trim.php