既然PHP是一种动态语言,那么检查所提供字段是否为空的最佳方法是什么?
我要确保:
Null被认为是空字符串 只有空格的字符串被认为是空的 那个“0”不是空的
这是我目前得到的:
$question = trim($_POST['question']);
if ("" === "$question") {
// Handle error here
}
一定有更简单的方法吧?
既然PHP是一种动态语言,那么检查所提供字段是否为空的最佳方法是什么?
我要确保:
Null被认为是空字符串 只有空格的字符串被认为是空的 那个“0”不是空的
这是我目前得到的:
$question = trim($_POST['question']);
if ("" === "$question") {
// Handle error here
}
一定有更简单的方法吧?
当前回答
这个检查数组和字符串:
function is_set($val) {
if(is_array($val)) return !empty($val);
return strlen(trim($val)) ? true : false;
}
其他回答
如果我错了,我会谦虚地接受,但我在自己的一端进行了测试,发现下面的代码可以用于测试字符串(0)""和NULL值变量:
if ( $question ) {
// Handle success here
}
这也可以反过来测试是否成功:
if ( !$question ) {
// Handle error here
}
当您希望检查字段是否提供了值时,该字段可能是字符串、数组或未定义的。所以,以下内容就足够了
function isSet($param)
{
return (is_array($param) && count($param)) || trim($param) !== '';
}
为了更健壮(制表,返回…),我定义:
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
// Function for basic field validation (present and neither empty nor only white space
function IsNullOrEmptyString($str){
return ($str === null || trim($str) === '');
}
这个检查数组和字符串:
function is_set($val) {
if(is_array($val)) return !empty($val);
return strlen(trim($val)) ? true : false;
}