isset empty php,PHP isset和empty 详细比较

最近写了一句判断的程序

点击(此处)折叠或打开

$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若是用==会和""相等,此时可能需要用强制等于来判断===

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值