最近写了一句判断的程序
点击(此处)折叠或打开
$switchType= empty($switchType)? 'all' : $switchType;
也就是在$switchType为空的情况下赋值为all,发现当$switchType为0的时候会发现$switchType也被赋值为all,因此可以认定php中0这个值在empty函数中会被作为空来判定,后来该为用isset就解决了此问题。根据这个问题,通过实际例子详细来解释下empty和issset两者的区域和用法。
一、empty和isset函数详解
1、empty函数
用途:检测变量是否为空
判断:如果 var 是非空或非零的值,则 empty() 返回 FALSE。换句话说,""、0、"0"、NULL、FALSE、array()、var $var; 以及没有任何属性的对象都将被认为是空的,如果 var 为空,则返回 TRUE。来源手册:2、isset函数
用途:检测变量是否设置
判断:检测变量是否设置,并且不是 NULL。如果已经使用 释放了一个变量之后,它将不再是 isset()。若使用 isset() 测试一个被设置成 NULL 的变量,将返回 FALSE。同时要注意的是一个NULL 字节("\0")并不等同于 PHP 的 NULL 常数。
二、测试例子
点击(此处)折叠或打开
function test($test_value) {
var_dump($test_value);
if (empty($test_value)) {
echo $test_value . " empty\n";
}
else {
echo $test_value . " not empty\n";
}
if (isset($test_value)) {
echo $test_value . " isset\n";
}
else {
echo $test_value . " not isset\n";
}
if ($test_value == "") {
echo $test_value . " the string empty\n";
}
else {
echo $test_value . " the string not empty\n";
}
}
$test_value = 0;
test($test_value);
echo "-----------------------\n";
$test_value = NULL;
test($test_value);
echo "-----------------------\n";
$test_value = "";
test($test_value);
echo "-----------------------\n";
$test_value = "\0";
test($test_value);
echo "-----------------------\n";
$test_value = array();
test($test_value);
echo "-----------------------\n";
$test_value = false;
test($test_value);
echo "-----------------------\n";
$test_value = true;
test($test_value);
echo "-----------------------\n";
?>
结果:
点击(此处)折叠或打开
int(0)
0 empty
0 isset
0 the string empty
-----------------------
NULL
empty
not isset
the string empty
-----------------------
string(0) ""
empty
isset
the string empty
-----------------------
string(1) ""
not empty
isset
the string not empty
-----------------------
array(0) {
}
Array empty
Array isset
Array the string not empty
-----------------------
bool(false)
empty
isset
the string empty
-----------------------
bool(true)
1 not empty
1 isset
1 the string not empty
-----------------------
三、两者区别
1、isset值对于变量没有赋值或者赋值为NULL时判断false,其余都是true;
2、empty需要注意点比较多,要根据函数的定义来做判断
四、使用注意
empty在用于判断比对的时候要多注意,0若是用==会和""相等,此时可能需要用强制等于来判断===