In PHP, isset() and empty() are commonly used to validate variables, especially when handling form data.
The isset() function checks whether a variable is declared and holds a value other than null. It returns false if the variable is not set or explicitly assigned null. If multiple variables are passed to isset(), it returns true only if all of them are set and not null.
$var = '';
if (isset($var)) {
echo "Variable exists and is not null";
}
$a = "example";
$b = "another";
var_dump(isset($a)); // true
var_dump(isset($a, $b)); // true
unset($a);
var_dump(isset($a)); // false
var_dump(isset($a, $b)); // false
$foo = null;
var_dump(isset($foo)); // false
On the other hand, empty() determines whether a variable is considered "empty" according to PHP's loose comparison rules. It returns true for values such as an empty string (""), integer 0, float 0.0, string "0", null, false, an empty array, or an undeclared variable. Importantly, empty() does not generate a warning if the variable is undefined.
$value = 0;
if (empty($value)) {
echo '$value is empty'; // This will execute
}
if (!isset($value)) {
echo '$value is not set'; // This will NOT execute
}
Key distinctions:
- Use
isset()to verify that a variable has been declared and is notnull. - Use
empty()to check if a variable is either undeclared or holds a value that evaluates tofalsein a boolean context. - To ensure a variable both exists and contains a non-empty value, combine both checks:
isset($var) && !empty($var)(though in practice,!empty($var)often suffices since it implies existence).