Is there any reason to use isset()?

人盡茶涼 提交于 2019-12-07 22:56:38

问题


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:

  1. false
  2. 0
  3. ""

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!