Pages

6/20/2012

PHP - POST an array

Those familiar with HTML know how to submit form entries to the server. Form values become accessible to the server based on the element's "name" attribute. Take the following form for example:

<form method="post" action="index.php">
        First Name: <input name="fname" type="text" />
        Last Name: <input name="lname" type="text" />
        <input type="submit" value="Submit" />
</form>

When the form is submitted, the form values can be access in PHP with the $_POST or $_REQUEST superglobal variables. To get the "First Name" that was submitted, simply use $_POST["fname"] or $_REQUEST["fname"]. Easy.

Now, if you want to use checkboxes, you don't have to use a different name for each checkbox (that could get messy in your PHP code). Instead, you can give all checkboxes in a group the same name. The trick is that you submit the checkbox values to an array (much easier to deal with in PHP - as long as the checkboxes are closely related). Example:

    <input name="os[]" type="checkbox" value="Linux" />
    <input name="os[]" type="checkbox" value="Windows" />
    <input name="os[]" type="checkbox" value="Mac" />
    <input name="os[]" type="checkbox" value="Other" />

Notice the brackets "[]" at the end of the name? This means it is an array. PHP will literally add each checked value as a new element at the end of the array. Then you can loop through the array in PHP:

$osSelections = $_POST["os"];
foreah($osSelections as $selection) {
        // Do stuff
}

This is still basic - nothing too exiting yet.

What I learned the other day is pretty neat. Since PHP has associative arrays (where strings are used as the array index instead of ordered numbers), you can specify a key for array elements. For example:

    <input name="submission[fname]" type="text" />

would be accessed in PHP with $_POST["submission"]["fname"]. That got you into a 2-dimension array. After years of dealing with HTML I never knew (or even thought) it was possible to specify the array key. You can even submit a multi-dimensional array like so:

    <input name="submission[os][]" type="checkbox" value="Linux" />

Pretty neat. You probably won't need to use it much, but it can come in handy in the right situation.

No comments:

Post a Comment