问题
Why should I use if (isset($var)) {}
rather than just if ($var) {}
? It seems to do the same thing and just take extra processing. Thanks!
回答1:
Reason
The reason is, isset()
will return boolean and doesn't throw a warning when you check for the existence of variable and proceed. Also, there is a possibility that, a variable may have zero values:
false
0
""
But they will be already set.
Example
$varb = false;
$vari = 0;
$vars = "";
isset($varb) // true
isset($vari) // true
isset($vars) // true
if ($varb) // false
if ($vari) // false
if ($vars) // false
回答2:
You use isset()
to check if a variable has been declared.
The other method checks what value $var
has. So if $var
happened to contain false
then the condition would be false but you wouldn't whether the variable wasn't set or the variable contained false
.
来源:https://stackoverflow.com/questions/15286321/is-there-any-reason-to-use-isset