PHP - Handling Empty Form Fields

Introduction

Users often forget to (or don't want to) fill in certain fields in a form.

When this happens, some data is not sent to the server.

Sometimes the field is sent as an empty string; sometimes no field name is sent at all.

The following table illustrates the behavior of various form controls when they're not filled in or selected:

Form Control What Happens When It's Not Filled In Or Selected
Text input field The field name is sent, along with an empty value.
Password fieldThe field name is sent, along with an empty value.
Checkbox fieldNothing is sent at all.
Radio button fieldNothing is sent at all.
Submit button Nothing is sent at all if the button isn't clicked. This can happen if the user presses Enter/Return to submit a form.
Reset button Nothing is ever sent.
File select field The field name is sent, along with an empty value.
Hidden field The field name is sent, along with an empty value.
Image field Same behavior as a submit button.
Push button Nothing is ever sent.
Pull-down menu Impossible to select no option, so a value is always sent.
List box Nothing is sent at all.
Multi-select boxNothing is sent at all.
Text area field The field name is sent, along with an empty value.

When nothing is sent at all for a field, PHP doesn't create an element for the field in the $_POST, $_GET, or $_REQUEST array.

So if you attempt to access the element, you'll generate a PHP notice along the lines of:

You can check if a field has value using PHP functions such as isset() or array_key_exists():

<dt>Gender</dt><dd><?php if (isset($_POST["gender"])) echo $_POST["gender"]?></dd>

Related Topic