Home >Backend Development >PHP Tutorial >Detailed introduction to the difference between php empty() and isset()_PHP tutorial

Detailed introduction to the difference between php empty() and isset()_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:05:56912browse

When using PHP to write page programs, I often use variable processing functions to determine whether a variable value at the end of the PHP page is empty. At the beginning, I was used to using the empty() function, but I found some problems, so Use the isset() function instead and the problem is gone.

As the name suggests, empty() determines whether a variable is "empty", and isset() determines whether a variable has been set. It is this so-called "as the name implies" that made me take some detours at the beginning: when a variable value is equal to 0, empty() will also be true (True), so some accidents will occur. It turns out that although empty() and isset() are both variable processing functions, they are both used to determine whether the variable has been configured, but they have certain differences: empty will also detect whether the variable is empty or zero. When a variable value is 0, empty() considers the variable to be equivalent to being empty, which is equivalent to not being set.

For example, to detect the $id variable, when $id=0, use empty() and isset() to detect whether the variable $id has been configured. Both will return different values ​​- empty() considers it not configured, isset () can get the value of $id:

Copy code The code is as follows:

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

This means that when we use the variable processing function, when the variable A value of 0 may occur, so be careful when using empty(). In this case, it is more sensible to replace it with isset.
When the URL tail parameter of a php page appears id=0 (for example: test.php?id=0), try to compare:
Copy code The code is as follows:

if(empty($id)) $id=1; - If id=0, id will also be 1
if(!isset($id)) $ id=1; - If id=0, id will not be 1

You can run the following code separately to detect the above inference:
Copy code The code is as follows:

if(empty($id)) $id=1;
print $id; // Get 1
if(!isset($id) ) $id=1;
print $id; //Get 0

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/327652.htmlTechArticleWhen writing page programs in PHP, I often use variable processing functions to determine the value of a variable at the end of the PHP page. Whether it is empty, I used to use the empty() function at the beginning,...
Statement:
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