phpisset

In where shall I use isset() and !empty()


I read somewhere that the isset() function treats an empty string as TRUE, therefore isset() is not an effective way to validate text inputs and text boxes from a HTML form.

So you can use empty() to check that a user typed something.

  1. Is it true that the isset() function treats an empty string as TRUE?

  2. Then in which situations should I use isset()? Should I always use !empty() to check if there is something?

For example instead of

if(isset($_GET['gender']))...

Using this

if(!empty($_GET['gender']))...

Solution

  • isset() checks if a variable has a value, including False, 0 or empty string, but not including NULL. Returns TRUE if var exists and is not NULL; FALSE otherwise.

    empty() does a reverse to what isset does (i.e. !isset()) and an additional check, as to whether a value is "empty" which includes an empty string, 0, NULL, false, or empty array or object False. Returns FALSE if var is set and has a non-empty and non-zero value. TRUE otherwise