PHP Multi-Values Form Fields

Summary: in this tutorial, we will show you how to handle multi-values form fields including checkboxes and multi-select list box in PHP.

Naming multi-valued form fields

In the previous tutorial, you learned how to create a simple contact form that contains fields with only single value. However, there are form fields that contain multiple values such as multi-select list box:

multi-select list box

and checkboxes with the same name but different values:

Checkboxes with the same name, but different values

When you submit those fields to the web server, those form fields send multiple values, rather than a single value. So how do you handle these multi-values fields in PHP? It’s kind of tricky. You need to add square brackets ( []) after the field name of the multi-valued form field. When PHP sees this sign ( []), it creates a nested array of values within the $_GET or $_POST array based on the method you use in the form.

The name of the multi-select list box should be formats[] and the name of the checkboxes should be sizes[]

Validating multi-valued form fields

When you submit the form that contains multi-valued form fields to the web server without selecting any item from a multi-select list box and or checking any checkbox, nothing is sent to the web server at all. Therefore you cannot handle the multi-values from fields like single-value form fields as follows:

Because the formats do not exist in the $_POST array, you will get an error message. To check if a multi-values field in submitted with value, you use the isset() function:

In addition, the values of the multi-values form fields are fixed, so you can check the submitted value against the predefined values. Suppose the allowed formats are stored in the $allowed_formats array, you can check the submitted value against the values in this array using the in_array() function:

To save time, you can generate multi-valued form fields based on the predefined values using PHP as follows:

Putting it all together

We will develop a banner ads design request form that contains multi-valued form fields as the following screenshot:

banner ads design request form

 

The logic of the banner ads design request form is similar to the contact form.

You can download the script file via the following link:

PHP Ads Banner Design Request Form (1389 downloads)

In this tutorial, we have shown you how to handle multi-valued form fields in PHP and show you step-by-step how to develop a banner ads design request form that contains multi-valued form fields.

  • Was this tutorial helpful ?
  • YesNo