The difference between php isset() and empty()

(*-*)浩
Release: 2023-02-25 21:50:01
Original
1930 people have browsed it

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 found some problems, so Use the isset() function instead and the problem no longer occurs.

The difference between php isset() and empty()

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 things will happen. Accident. (Recommended learning:PHP Video Tutorial)

It turns out that although empty() and isset() are both variable processing functions, they are 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( ) that there is no configuration, isset() can get the value of $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 .
Copy after login

This means that when we use the variable processing function, when the variable may have a value of 0, be careful when using empty(), It would be wiser to replace it with isset at this time.

When the URL tail parameter of a php page appears id=0 (for example: test.php?id=0), try to compare:

if(empty($id)) $id=1; - 若 id=0 ,id 也会为1 if(!isset($id)) $id=1; - 若 id=0 ,id 不会为1
Copy after login

You can run the following code separately to detect the above inference:

if(empty($id)) $id=1; print $id; // 得到 1 if(!isset($id)) $id=1; print $id; //得到 0
Copy after login

The above is the detailed content of The difference between php isset() and empty(). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
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
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!