Home > Backend Development > PHP Tutorial > When to Use 'isset()' vs. '!empty()' in PHP?

When to Use 'isset()' vs. '!empty()' in PHP?

DDD
Release: 2024-11-10 17:52:02
Original
887 people have browsed it

When to Use 'isset()' vs. '!empty()' in PHP?

Understanding the Distinction Between 'isset()' and '!empty()' in PHP

The operators 'isset()' and '!empty()' are often used in PHP to verify the existence or emptiness of variables. However, their functionalities differ subtly.

isset() evaluates whether a variable has been assigned a value, regardless of its value. This includes non-empty values such as strings, arrays, and objects. isset() returns TRUE if the variable is defined and not null, irrespective of its content.

!empty(), on the other hand, examines whether a variable contains an actual, non-empty value. It considers empty values as:

  • Empty strings ("")
  • Zero (integer) or zero-like values ("0")
  • Null values (NULL)
  • False boolean values (FALSE)
  • Empty arrays ([])
  • Undeclared class variables ("$var;")

Therefore, !empty() returns TRUE only if the variable contains a non-empty string, a non-zero number, a non-null value, a non-FALSE boolean, a non-empty array, or a declared class variable with a value.

To illustrate the difference, consider the following examples:

<?php
$var1 = "Hello";
$var2 = "";
$var3 = 0;
$var4 = NULL;
$var5 = [];

var_dump(isset($var1)); // TRUE (variable defined and not null)
var_dump(isset($var2)); // FALSE (variable defined but empty string)
var_dump(isset($var3)); // FALSE (variable assigned zero)

var_dump(!empty($var1)); // TRUE (non-empty string)
var_dump(!empty($var2)); // FALSE (empty string)
var_dump(!empty($var3)); // FALSE (zero value)
var_dump(!empty($var4)); // FALSE (NULL value)
var_dump(!empty($var5)); // FALSE (empty array)
?>
Copy after login

In summary, isset() verifies variable existence, while !empty() checks for non-empty values. Understanding this distinction is essential for effective variable handling and preventing errors in PHP code.

The above is the detailed content of When to Use 'isset()' vs. '!empty()' in PHP?. For more information, please follow other related articles on the PHP Chinese website!

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