Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

isset

isset vs. !empty

FTA:

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

On the other hand the empty() function checks if the variable has an empty value empty string, 0, NULL or False. Returns FALSE if var has a non-empty and non-zero value."


In the most general way :

  • isset tests if a variable (or an element of an array, or a property of an object) exists (and is not null)
  • empty tests if a variable (...) contains some non-empty data.


To answer question 1 :

$str = '';
var_dump(isset($str));

gives

boolean true

Because the variable $str exists.


And question 2 :

You should use isset to determine whether a variable exists ; for instance, if you are getting some data as an array, you might need to check if a key isset in that array.
Think about $_GET / $_POST, for instance.

Now, to work on its value, when you know there is such a value : that is the job of empty.


Neither is a good way to check for valid input.

  • isset() is not sufficient because – as has been noted already – it considers an empty string to be a valid value.
  • ! empty() is not sufficient either because it rejects '0', which could be a valid value.

Using isset() combined with an equality check against an empty string is the bare minimum that you need to verify that an incoming parameter has a value without creating false negatives:

if( isset($_GET['gender']) and ($_GET['gender'] != '') )
{
  ...
}

But by "bare minimum", I mean exactly that. All the above code does is determine whether there is some value for $_GET['gender']. It does not determine whether the value for $_GET['gender'] is valid (e.g., one of ("Male", "Female","FileNotFound")).

For that, see Josh Davis's answer.


isset is intended to be used only for variables and not just values, so isset("foobar") will raise an error. As of PHP 5.5, empty supports both variables and expressions.

So your first question should rather be if isset returns true for a variable that holds an empty string. And the answer is:

$var = "";
var_dump(isset($var));

The type comparison tables in PHP’s manual is quite handy for such questions.

isset basically checks if a variable has any value other than null since non-existing variables have always the value null. empty is kind of the counter part to isset but does also treat the integer value 0 and the string value "0" as empty. (Again, take a look at the type comparison tables.)