When working with forms in HTML and PHP, it is sometimes desirable to have input elements that are stored as arrays in the resulting POST data. However, it can be challenging to achieve this, especially when the elements are added dynamically.
The Issue: Nested Elements and Array Structure
Consider the following form markup:
<form> <input type="text" name="levels[level]"> <input type="text" name="levels[build_time]"> <input type="text" name="levels[level]"> <input type="text" name="levels[build_time]"> </form>
This form will result in a POST array with nested elements, as shown below:
Array ( [1] => Array ( [level] => 1 [build_time] => 123 ) [2] => Array ( [level] => 2 [build_time] => 456 ) )
However, it would be more convenient to have an array structure like this:
Array ( [0] => Array ( [level] => 1 [build_time] => 123 ) [1] => Array ( [level] => 2 [build_time] => 456 ) )
The Solution: Array Syntax
To achieve this array structure, simply add square brackets [] to the end of the input element names, like so:
<input type="text" name="levels[level][]"> <input type="text" name="levels[build_time][]">
This modification allows PHP to interpret the input elements as an array of values. When the form is submitted, you will get the desired array structure.
Dynamically Adding Elements
Note that you can use a loop to dynamically add these input elements, making it easy to add as many pairs of "level" and "build_time" elements as needed.
The above is the detailed content of How Can I Create and Manage Arrays from HTML/PHP Form Inputs?. For more information, please follow other related articles on the PHP Chinese website!