php empty,isset,is_null判断比较(差异与异同)

2019-04-09 14:00:05王冬梅
一、举例说明
A.一个变量没有定义,我们该怎么样去判断呢

<?php
#不存在$test 变量

$isset= isset($test)?"test is define!":"test is undefine!";
echo "isset:$issetrn";

$empty=!empty($test)?"test is define!":"test is undefine!";
echo "empty:$emptyrn";

$is_null=is_null($test)?"test is define!":"test is undefine!";
echo "is_null:$is_nullrn";

测试结果是:

结果出来了:empty,isset首先都会检查变量是否存在,然后对变量值进行检测。而is_null 只是直接检查变量值,是否为null,因此如果变量未定义就会出现错误!

B、看下各自接收的参数是什么?

isset函数参数:

<?php
$test=100;
echo isset($test),isset(100),$isset($b=100);

 

<br />
<b>Parse error</b>:  parse error, unexpected T_LNUMBER, expecting T_STRING or T_VARIABLE or '$' in <b>PHPDocument3</b> on line <b>3</b><br />

empty函数参数:

<?php
$test=100;

echo empty($test),empty(100),empty($b=100);

 

<br />
<b>Parse error</b>:  parse error, unexpected T_LNUMBER, expecting T_STRING or T_VARIABLE or '$' in <b>PHPDocument3</b> on line <b>3</b><br />

is_null函数参数:

<?php
$test=100;

echo is_null($test),is_null(100),is_null($b=100);

运行结果:没有任何错误。

比较结果出来了:empty,isset输入参数必须是一个变量(php变量是以$字符开头的),而is_null输入参数只要是能够有返回值就可以。(常量,变量,表达式等)。在php手册里面,对于他们解析是:empty,isset 是一个语言结构而非函数,因此它无法被变量函数调用。

二、概括总结isset,empty,is_null区别:
刚才介绍的:检查变量,以及参数类型,这个是这3个函数不同之处的基础,也是最容易被忽视的。看到网上有很多对这个3个函数进行比较文章。很少涉及这些。下面我要说的,是在都检查已存在变量情况下,不同之处。

实例:


<?php
$a=100;
$b="";
$c=null;
//isset检查
echo "isset","$a=$a",isset($a)?"define":"undefine","rn";
echo "isset","$b=$b",isset($b)?"define":"undefine","rn";
echo "isset","$c=$c",isset($c)?"define":"undefine","rn";
unset($b);
echo "isset","$b",isset($b)?"define":"undefine","rn";
$b=0;
echo "rnrn";

//empty检查
echo "empty","$a=$a",!empty($a)?"no empty":"empty","rn";
echo "empty","$b=$b",!empty($b)?"no empty":"empty","rn";
echo "empty","$c=$c",!empty($c)?"no empty":"empty","rn";
unset($b);
echo "empty","$b",!empty($b)?"no empty":"empty","rn";
$b=0;
echo "rnrn";

//is_null检查
相关文章 大家在看