Generate Arrays in PHP from HTML Form Field Values

Large HTML Forms are tedious to work with. When using PHP to receive the Form Field Values it sometimes can be helpful to use this trick to get the Form Data as Array

To cast Form <input> values to an Array the name Attribute expression needs to end with brackets [].

<input type="checkbox" name="food[]" value="indian" id="indian"> <!-- [X] -->
<input type="checkbox" name="food[]" value="mexican" id="mexican"> <!-- [x] -->
<input type="checkbox" name="food[]" value="austrian" id="austrian"> <!-- [] -->

When the Form is processed with PHP the Superglobals $_POST / $_GET and $_REQUEST will be set to an Array and the <input> Field value attribute will be set as Array item.

<pre>
<?php print_r($_POST); ?>
</pre>
[food] => Array
(
[0] => indian
[1] => mexican
)

It is also possible to define the Array keys to create a named multidimensional Array as shown below.

<input type="text" name="contact[private][street]" id="privateStreet"> <!-- Address Test 1/1 -->
<input type="text" name="contact[private][city]" id="privateCity"> <!-- Vienna -->
<input type="text" name="contact[company][street]" id="companyStreet"> <!-- Address Test 2/2 -->
<input type="text" name="contact[company][city]" id="companyCity"> <!-- Reykjavik -->
<pre>
<?php print_r($_POST); ?>
</pre>
[contact] => Array
(
[private] => Array
(
[street] => Address Test 1/1
[city] => Vienna
)

[company] => Array
(
[street] => Address Test 2/2
[city] => Reykjavik
)

)

With this technique it is possible to collect data for the same context. Another Example which comes to mind could be multiple Email addresses for a single User. Receiving Data Arrays on the Backend can make it a lot easier to handle large amounts of Form Data.