教程集 www.jiaochengji.com
教程集 >  脚本编程  >  php  >  正文 PHP isset和empty的用法分析

PHP isset和empty的用法分析

发布时间:2017-05-16   编辑:jiaochengji.com
本文介绍下,在php编程中,有关isset和empty的用法区别,有需要的朋友参考下。

本节内容:
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。来源手册:http://php.net/manual/zh/function.empty.php
注意:empty() 只检测变量,检测任何非变量的东西都将导致解析错误。换句话说,后边的语句将不会起作用: empty(addslashes($name))

2、isset函数
用途:检测变量是否设置
判断:检测变量是否设置,并且不是 NULL。如果已经使用 unset() 释放了一个变量之后,它将不再是 isset()。若使用 isset() 测试一个被设置成 NULL 的变量,将返回 FALSE。同时要注意的是一个NULL 字节("\0")并不等同于 PHP 的 NULL 常数。

二、测试例子
 

复制代码 代码示例:

<?php
/**
* isset和empty用法区别
* by www.jbxue.com
*/
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若是用==会和""相等,此时可能需要用强制等于来判断===。

您可能感兴趣的文章:
php empty(),isset()与is_null()的用法区别分析
实例解析PHP中empty,is_null和isset的用法区别
PHP isset和empty的用法分析
PHP isset与empty使用举例
浅析php中empty与isset区别
php isset函数的用法举例
empty()和isset()函数的区别
php empty()与isset()函数区别分析
php数组判断键值是否存在示例
php中empty(), is_null(), isset()函数区别

[关闭]
~ ~