Why do I need the isset() function in php?
Asked Answered
P

6

13

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?

Pastorate answered 17/3, 2010 at 6:36 Comment(0)
B
20

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)

Burgenland answered 17/3, 2010 at 6:38 Comment(4)
so should I just always use the isset function in cases like these?Pastorate
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.Blister
@Chris: Always use isset to check the existence of a certain variable.Burgenland
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 variableAltitude
S
4

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

Suet answered 17/3, 2010 at 6:38 Comment(0)
C
3

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.

Carminacarminative answered 17/3, 2010 at 6:41 Comment(0)
Y
1

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.

Yttriferous answered 17/3, 2010 at 6:50 Comment(0)
B
0

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. :)

Brook answered 17/3, 2010 at 9:51 Comment(1)
This sounds more like default error handling setup then an operating system.Yttriferous
F
0

if user do not enter a value so $_post[] return NULL that we say in the description of isset:"

isset will return TRUE if it exists and is not NULL otherwise it is FALSE.,but in here isset return the true "

Fetish answered 13/8, 2013 at 5:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.