Home  >  Article  >  Backend Development  >  The difference between php isset() and empty()

The difference between php isset() and empty()

(*-*)浩
(*-*)浩Original
2019-10-09 11:42:191949browse

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 "<br>";
    !isset($id)?print "It&#39;s empty .":print "It&#39;s $id .";
      //结果:It&#39;s 0 .

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

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

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!

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
Previous article:What is PDO in phpNext article:What is PDO in php