Backend Development 4 min read

Understanding PHP isset() and empty() Functions

This article explains the purpose, syntax, return values, and usage nuances of PHP's isset() and empty() functions, provides code examples with expected output, and compares their behavior when checking variable existence and emptiness.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Understanding PHP isset() and empty() Functions

The isset() function checks whether a variable is set and not null . Its signature is isset(mixed $var, mixed $... = ?): bool . It returns true if the variable exists and its value is not null , otherwise false . If a variable has been unset() , isset() will return false . When multiple arguments are passed, isset() returns true only if all arguments are set; evaluation stops at the first unset variable.

<code>&lt;?php
  $num = '0';
  if (isset($num)) {
      print_r("$num is set with isset");
  }
  echo "<br>";
  // Declare an empty array
  $array = array();
  echo isset($array['geeks']) ? 'array is set.' : 'array is not set.';
?&gt;</code>

Output: 0 is set with isset functionarray is not set.

The empty() function determines whether a variable is considered empty. Its signature is empty(mixed $var): bool . It returns true when the variable is not set, is null , an empty string, the integer 0 , the float 0.0 , the string "0" , false , an empty array, or an uninitialized variable; otherwise it returns false .

<code>&lt;?php
$temp = 0;
if (empty($temp)) {
    echo $temp . ' is considered empty';
}
echo "\n";
$new = 1;
if (!empty($new)) {
    echo $new . ' is considered set';
}
?&gt;</code>

Output: 0 is considered empty 1 is considered set

Both isset() and !empty() can be used to test variable existence, but empty() does not generate a warning when the variable does not exist, making it safer for such checks. Using both together can cause unnecessary performance overhead.

<code>&lt;?php
$num = '0';
if (isset($num)) {
    print_r($num . " is set with isset function");
}
echo "\n";
$num = 1;
if (!empty($num)) {
    print_r($num . " is set with !empty function");
}
?&gt;</code>

Output: 0 is set with isset function 1 is set with !empty function

backendPHPFunctionsVariablesemptyisset
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.