views:

146

answers:

5

I am trying to understand the difference between this:

if (isset($_POST['Submit'])) { 
  //do something
}

and

if ($_POST['Submit']) { 
  //do something
}

It seems to me that if the $_POST['Submit'] variable is true, then it is set. Why would I need the isset() function in this case?

+8  A: 

Because

$a = array("x" => "0");

if ($a["x"])
  echo "This branch is not executed";

if (isset($a["x"]))
  echo "But this will";

(See also http://hk.php.net/manual/en/function.isset.php and http://hk.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting)

KennyTM
so should I just always use the isset function in cases like these?
zeckdude
Trying to access `$a["x"]` will also raise an `E_Notice` when there is no key `x` defined inside `$a`. Checking with `isset` or `array_key_exists` can avoid this.
Gordon
@Chris: Always use `isset` to check the *existence* of a certain variable.
KennyTM
Also the isset function prevents a warning in case the variable is not set. If you do this if ($bla) and there is no bla, php will issue a warning saying that there is no $bla variable
AntonioCS
+1  A: 

isset will return TRUE if it exists and is not NULL otherwise it is FALSE.

Kevin
+2  A: 

You basically want to check if the $_POST[] variable has been submitted at all, regardless of value. If you do not use isset(), certain submissions like submit=0 will fail.

Crimson
+1  A: 

In your 2nd example, PHP will issue a notice (on E_NOTICE or stricter) if that key is not set for $_POST.

Also see this question on Stack Overflow.

alex
Not `E_STRICT`; `E_NOTICE`.
janmoesen
Ah cheers, thanks.
alex
A: 

The code


if($_POST['Submit'])
{
//some code
}

will not work in WAMP (works on xampp)
on WAMP you will have to use


if (isset($_POST['Submit'])) { 
  //do something
}

try it. :)

Gaurav Sharma
This sounds more like default error handling setup then an operating system.
alex