Many people tend to view these two functions as opposites, causing necessary debugging. This issue frequently occurs when validating forms.
isset()
From the PHP manual:
isset — Determine if a variable is set and is not NULL
In other words, a variable is set if it has been assigned a value other than NULL. If a variable is assigned to be an empty string – it is set. The following code and output should illustrate my point.
[code lang="PHP"]
var_dump(isset($x));
$x = NULL;
var_dump(isset($x));
$x = "";
var_dump(isset($x));
$x = '';
var_dump(isset($x));
?>[/code]
bool(false)
bool(true)
bool(true)
empty()
Again from the PHP manual:
empty — Determine whether a variable is empty
In other words, a variable is empty if it is an empty string, 0, “0″, false, NULL, array(), and an unset variable are all empty.
[code lang="PHP"]
var_dump(empty($x));
$x = NULL;
var_dump(empty($x));
$x = "";
var_dump(empty($x));
$x = '';
var_dump(empty($x));
$x = "0";
var_dump(empty($x));
$x = 0;
var_dump(empty($x));
$x = false;
var_dump(empty($x));
$x = array();
var_dump(empty($x));
?>[/code]
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
Now when you are validating forms to make sure a user did not leave a form field blank, it is probably best to use neither empty() or isset() (not that isset would work). Since it is possible your form might accept 0 as a valid answer. Therefore you should just check to make sure it is not an empty string.
[code lang="PHP"]
if($_GET['foo'] == "") {
echo "You must enter a value for foo!";
}
?>[/code]
9. January 2010
7 Comments »