Submit an Array with a HTML Form

Submit an Array with a HTML Form

   1 Comment   
http://bit.ly/1Op8xW7
Mail in your door

Most of us will know how HTML forms work: inputs contained within the form send data to a url, by either a GET or POST request. This will result in the server being able to access this data on the other end.

The way to do this usually goes something like this:

<form action="" method="POST">
    <input type="text" name="first_name">
    <input type="text" name="last_name">
    <input type="submit">
</form>

// Result of $_POST (PHP):
// array(
//     'first_name' => ''
//     'last_name' => ''
// )

Interestingly, and to the point of this post, you can also post an array of data with a form by using square brackets. If you place something within the square brackets then the resulting array becomes associative, otherwise it’ll be numeric.

<form action="" method="POST">
    <input type="text" name="name[first]">
    <input type="text" name="name[last]">
    <input type="submit">
</form>

// Result of $_POST (PHP):
// array(
//     'name' => array(
//         'first' => ''
//         'last' => ''
//     )
// )

Checkboxes

This method makes submitting names and address neater. However, one of the biggest differences is when using checkboxes, as they don’t need a different name for each input, one name, one array, multiple values – no more huge isset checking statements!

<form action="" method="POST">
    <input type="checkbox" name="role[]" value="1" id="admin">
    <label for="admin">Admin</label>

    <input type="checkbox" name="role[]" value="2" id="publisher">
    <label for="publisher">Publisher</label>

    <input type="submit">
</form>

// Result of $_POST (if all are checked):
// array(
//     'role' => array(1, 2)
// )

As you can see this is a much neater way of submitting data with forms, both from a html and a server side point of view.



One response to “Submit an Array with a HTML Form

Leave a Reply

Your email address will not be published. Required fields are marked *