Empty() and Isset() in PHP

This is just a quick tutorial regarding the empty() and isset() functions for people that are fairly new to the world of PHP programming. I learned this the hard way a long time ago while I was working on my first few form processors in PHP.

From the PHP Web site, referring to the empty() function:

Returns FALSE if var has a non-empty and non-zero value.

That’s a good thing to know. In other words, everything from NULL, to 0 to “” will return TRUE when using the empty() function.
Here is the description of what the isset() function returns:

Returns TRUE if var exists; FALSE otherwise.

In other words, only variables that don’t exist (or, variables with strictly NULL values) will return FALSE on the isset() function. All variables that have any type of value, whether it is 0, a blank text string, etc. will return TRUE.

Something else you need to know is that textareas and textboxes in forms will be sent with “” values rather than NULL values to the $_POST[] array.

Therefore, if you are trying to process a form, and you want to make sure the person entered something into the field, you are much better off checking to see if the form value is empty, than you are checking to see if it isset(). On the other hand, if you are trying to check the value of a radio button or combobox in which one of your possible values is “0”, then you should be using the isset() function.

For the first few form processors I worked on, I was consistently using the following code:

if(isset($_POST[myField]) && $_POST[myField] != "") 
{
  //Do my PHP code
}

A more efficient way of doing this is obviously to use:

if(!empty($_POST[myField])) 
{
  //Do my PHP code
}

Just a quick tip for people struggling with this. There are two main points in this article:

1) isset() and empty() are not exactly opposite of each other. They actually check for two very different things. Therefore, using !isset() is not the same as using empty(), nor is “!empty” the same as using isset(). That’s a good thing, but it’s not something you generally figure out right off the bat.

2) Forms will send blank values to the $_POST[] array instead of sending NULL values. Therefore, the variable you are usually checking from your form is, in the strictest sense of the word, “set”. However, it may still have an “empty” value. Therefore, if you really only want to check to see if the variable exists, even if it has an empty value (or if you want to check if a variable doesn’t exist), then you want to use the isset() function. However, if you want to check to see if the variable has (or doesn’t have) an empty value, then you are better off using the empty function.

I hope that helps someone out there avoid some of the coding mistakes I made early in the game. Enjoy.

Did you like this post? Get monthly summary of our new tutorials, posts and tips to your inbox!


Developer Resources