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.
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><?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.';
?></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><?php
$temp = 0;
if (empty($temp)) {
echo $temp . ' is considered empty';
}
echo "\n";
$new = 1;
if (!empty($new)) {
echo $new . ' is considered set';
}
?></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><?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");
}
?></code>Output: 0 is set with isset function 1 is set with !empty function
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.