Submit an Array with a HTML Form

Submit an Array with a HTML Form

   6 Comments    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.



6 responses to “Submit an Array with a HTML Form

    1. Hi Nigel, these are just to illustrate the point on how they might appear when sent though to a server-side language like PHP

  1. Hi, how would one check for values inside of these arrays? Let’s say I make an array inside of my form tag, name=”role[admin]”, and I wan’t to check if the value is set, how would one do that?

    For example:

    if(!empty($_POST['role["admin"]'}){
    echo 'value exists'!
    };

    I want to check if [admin] is empty or not.

    Why does this not work? Can't figure it out after Googling for 1+ hours.
    Help would be appreciated.

    Also, echo $_POST['role["admin"]']; also does not work, probably because it is a multidimensional array?
    print_r() works though..

    1. Hi Dennis, you’re so close. This should work (without inner quotes):

      if (!empty($_POST['role']['admin']) {
          echo ‘value exists’!
      }

Leave a Reply

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