检查变量是否为空

41
if ($user_id == NULL || $user_name == NULL || $user_logged == NULL) {
    $user_id = '-1';
    $user_name = NULL;
    $user_logged = NULL;
}
if ($user_admin == NULL) {
    $user_admin = NULL;
}
  1. 有没有更短的方法来做这件事情?
  2. 如果我没错,应该用 is_null 进行测试吗?
  3. 是否可以将 $user_id$user_name$user_logged 写在一行中(可能是数组),而不需要重复写 NULL

请问有没有更好的方法来检查变量是否为null或空字符串? - user745235
我觉得你可以为此创建一个函数... - user745235
12个回答

0
感觉有必要回答一下,因为其他回答不够准确。如果可以的话,请使用empty(),因为它覆盖了更多的情况。未来的你会感谢我的。
例如,你将不得不执行像isset() && strlen()这样的操作,而你可以使用empty()代替。把它想象成这样:empty就像!isset($var) || $var==false。

0
<?php

$nothing = NULL;
$something = '';
$array = array(1,2,3);

// Create a function that checks if a variable is set or empty, and display "$variable_name is SET|EMPTY"
function  check($var) {
    if (isset($var)) {
        echo 'Variable is SET'. PHP_EOL;
  } elseif (empty($var)) { 
        echo 'Variable is empty' . PHP_EOL;

   } 

} 

check($nothing);
check($something);
check($array);

提供详细的答案。 - Parixit
相关阅读:为什么要同时检查isset()和!empty() - mickmackusa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接