PHP中如何判断一个变量是否为空
答案:使用PHP empty()函数
您可以使用 PHP empty() 函数来确定 变量 是否为空。 如果变量不存在或其值等于 FALSE,则认为该变量为空。
让我们尝试以下示例来了解此功能的基本工作原理:
<?php
$var1 = '';
$var2 = 0;
$var3 = NULL;
$var4 = FALSE;
$var5 = array();
// 测试变量
if(empty($var1)){
echo 'This line is printed, because the $var1 is empty.';
}
echo "<br>";
if(empty($var2)){
echo 'This line is printed, because the $var2 is empty.';
}
echo "<br>";
if(empty($var3)){
echo 'This line is printed, because the $var3 is empty.';
}
echo "<br>";
if(empty($var4)){
echo 'This line is printed, because the $var4 is empty.';
}
echo "<br>";
if(empty($var5)){
echo 'This line is printed, because the $var5 is empty.';
}
?>
注意:如果变量不存在,empty() 函数不会生成警告。 这意味着 empty() 等价于 !isset($var) || $var == false。
FAQ 相关问题解答
以下是与此主题相关的更多常见问题解答:
Advertisements
