Capture and Validate Multi-Value Form Data in PHP

I am not going to make this tutorial unnecessarily long so you won’t get bored rather I will as much as possible make this article brief and succinct.

When writing HTML form, form element such as <checkbox> and <select multiple> are used for capturing multi-value data.

Below is an example code for an HTML form consisting of a multi-select and checkbox element.

Note: the form will be secretly sent to validate.php via POST method.

Take cognizance of the double square bracket [] succeeding the value of the name attribute in both the select and checkbox element.
The presence of the double squared brackets makes it possible to capture the multi-value data as an array.

Capturing Multi-valued Form Data

To capture the data which is an array, loop through the array of data using PHP foreach and echo out the “fruits you love” and the “food you hate”.

Validating Array of Form Data

We have seen how to configure our form to send the multi-valued data as an array to validate.php and also capture loop through each array data and display them.
Finally, let’s see how to validate the array data.

Remember, never trust the users.

To keep things simple, we will write a function that only strip out any HTML and PHP tag from the captured array element.

We will be using PHP’s array_map() to return the data array after applying our custom validation function to each array element.

Let’s see the code.

Firstly, we create a function validate that handles the HTML and PHP tag stripping.
The function is next applied to the array element of “fruits you love” and “food you hate” and later the validated array is stored in $fruitData and $foodData variable respectively.

Note: your validate function can contain complex validation rules. For simplicity, I chose to strip out HTML and PHP tag only.

Since our validation is just the stripping of HTML and PHP tag using strip_tags function, you could reduce your code count by removing the validate function and passing the strip_tags as a callback function to array_map as follows:


In this article, I taught us how to capture multi-values form data as an array and perform a validation check on the array element.

Happy coding!

About Agbonghama Collins

Agbonghama Collins is a webdeveloper and an internet geek. I love writing and sharing the little idea & information i know. Hope you enjoyed my Article.

Follow me on Twitter, add him on Facebook or on Google+