有没有理由使用isset()?

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!

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

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.