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]
Good article. Just found another over at Tutorial Arena that takes a more in depth look at the difference between the two: PHP isset vs empty
Hope these 2 articles help someone.
|
Great advise. For my $_GET / POST / REQUEST I use this simple function to automatically check if the value is set and avoid any undefined index warnings.
<code>
//GET
function GV($key,$default=""){
return (isset($_GET[$key])) ? $_GET[$key] : $default;
}
</code>
I did a quick write up about using this function here: quick php get post request isset function
|
And what happens if $_GET['foo'] is not defined? You will get "Undefined index: foo" error
From my own experience you should always use isset()
i.e: if ((isset($_GET['foo'])) && ($_GET['foo'] == "")) { … your code here … }
|
forgot to mention this approach
<code>
$foo = (isset($_GET['foo'])) ? $_GET['foo'] : '';
if ($foo == '') { … code here … }
</code>
|
Thanks for pointing that out. I was more interested in describing the differences between the two functions rather than trying to provide "best practice" approach to using them. But you are right, my code will cause a notice to be displayed, and I will amend it to reflect your suggestions.
|
Good post, i recently [also] discovered that testing with a 0 will return true if empty() is used. The implications are obvious and since then i always check if the string is empty ( $variable == '' ) instead of using if ( empty($variable) )
|