Home >Backend Development >PHP Problem >The difference between php isset() and empty()
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.
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's empty .":print "It's $id ."; //结果:It'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!