Home >Backend Development >PHP Tutorial >How to Create and Handle Array Input in HTML/PHP Forms?
Input as array in HTML/PHP Forms
When creating forms in HTML that receive user input, there are instances where you may want to collect data in an array structure. This article explores how to achieve this using PHP input names.
Scenario:
Consider a form that includes multiple pairs of input fields, where each pair consists of a level and build_time. The desired output is an array with each pair stored as a subarray, resembling the following:
Array ( [1] => Array ( [level] => 1 [build_time] => 123 ) [2] => Array ( [level] => 2 [build_time] => 456 ) )
First Approach:
Initially, the form used static field names, such as name="levels[level]", which resulted in the following output:
[levels] => Array ( [0] => Array ( [level] => 1 ) [1] => Array ( [build_time] => 234 ) [2] => Array ( [level] => 2 ) [3] => Array ( [build_time] => 456 ) )
Corrected Approach:
To obtain the desired output format, the square brackets should be added to the end of the input names, as seen below:
<input type="text" class="form-control" placeholder="Titel" name="levels[level][]"> <input type="text" class="form-control" placeholder="Titel" name="levels[build_time][]">
With this revised approach, PHP will group the input values into subarrays based on the presence of the square brackets. The resulting array structure will align with the expected format.
Dynamically Adding Input Fields:
This corrected approach allows for dynamic addition of input fields, eliminating the need to specify indices within the form elements. PHP will automatically arrange them as subarrays, providing a convenient and flexible way to collect data.
Usage:
To retrieve the individual values, simply use PHP array syntax:
echo $levels["level"][5]; // Retrieves the 6th level echo $levels["build_time"][5]; // Retrieves the corresponding build time
The above is the detailed content of How to Create and Handle Array Input in HTML/PHP Forms?. For more information, please follow other related articles on the PHP Chinese website!