php空值_

WBOY
Release: 2016-06-13 13:04:35
Original
913 people have browsed it

php空值__

PHP空值判断

在使用 php 编写页面程序时,我经常使用变量处理函数判断 php 页面尾部参数的某个变量值是否为空,开始的时候我习惯了使用 empty() 函数,却发现了一些问题,因此改用 isset() 函数,问题不再。

顾名思义,empty 判断一个变量是否为“空”,isset 判断一个变量是否已经设置。正是这种所谓的“顾名思义”,令我开始时走了些弯路:当一个变量值等于0时,empty()也会成立(True),因而会发生 一些意外。原来,empty 和 isset 虽然都是变量处理函数,它们都用来判断变量是否已经配置,它们却是有一定的区别:empty还会检测变量是否为空、为零。当一个变量值为0,empty 认为这个变量同等于空,即相当于没有设置。

比如检测 $id 变量,当 $id=0 时,用empty 和 isset 来检测变量 $id 是否已经配置,两都将返回不同的值―― empty 认为没有配置,isset 能够取得 $id 的值:

??? $id=0;
??? empty($id)?print "It's empty .":print "It's $id .";
????? //结果:It's empty .
??? print "
";
??? !isset($id)?print "It's empty .":print "It's $id .";
????? //结果:It's 0 .

这意味着,我们在使用变量处理函数时,当该变量可能出现0的值,使用 empty 要小心,这个时候用 isset 取代它更明智一些。

当一个php页面的 URL 尾部参数出现 时(比如:test.php?id=0),试比较:

??? if(empty($id)) $id=1; - 若 ,id 也会为1
??? if(!isset($id)) $id=1; - 若 ,id 不会为1

可分开运行以下代码检测上述推断:

??? if(empty($id)) $id=1;
??? print $id; // 得到 1

??? if(!isset($id)) $id=1;
??? print $id; //得到 0

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!