Reputation: 7266
I am going through the "Head First PHP & MySQL" book right now, and on many parts of the book there are code snippets used to process HTML forms. They start like this:
if (isset($_POST['submit'])){
...
}
The if clause is used to detect if the form has been submitted already or not. Being used to programming in C mostly, I find that construct redundant and annoying (and I also don't think it helps code readability for experienced programmers). I would rather write it as:
if ($_POST['submit']){
...
}
Question: Is there some other reason to use isset() in this context that I might be missing? Would my version of the snippet be considered non-idiomatic PHP? What about in other contexts, can you give me an example of when isset() might be useful?
Upvotes: 2
Views: 193
Reputation: 69957
One of the biggest reasons I can think of is because of PHP's error_reporting and display_errors setting.
Let's say that error_reporting is set to E_ALL
and display_errors
is turned on.
If you tried to do something like: if ($array['iDontExist'] == false)
the code will run as expected, since the variable isn't set, it will evaluate to boolean false. The side effect however, is that PHP will emit a notice saying the variable $array['iDontExist']
does not exist. The more you have this, the more likely random notices will be spammed all over the output.
I find a LOT of production systems have error reporting turned on which would result in this unwanted behavior. If display_errors is turned off, the messages won't show up in the browser, but if error_reporting is set to track notices, the error_log
will contain all of the notices about undefined variables, which is also an annoyance.
Upvotes: 1
Reputation: 6239
Well, if $_SERVER
doesn't have the submit
key, the second block would throw an E_NOTICE
(Undefined index), therefore you should use isset()
if you want to check if that key exists and is not null (or, alternatively, array_key_exists()
, which just check for the existence).
Additionally, if you also want to check the content of the variable (for example, if it's set to false
or 0
), I'd suggest to use the !empty()
(note the negation with !
) function instead of isset()
.
Upvotes: 1
Reputation: 701
Check out this page for more information about isset()
http://php.net/manual/en/function.isset.php
Upvotes: 2
Reputation: 180014
There are situations where a variable is NULL
, 0
, or FALSE
. They'd fail the if() {}
comparison, but they are set.
Using isset()
also avoids a notice about an undefined variable if your error_reporting settings include E_NOTICE
s.
Upvotes: 9