Home > Backend Development > PHP Tutorial > How Can I Create and Manage Arrays from HTML/PHP Form Inputs?

How Can I Create and Manage Arrays from HTML/PHP Form Inputs?

Susan Sarandon
Release: 2024-12-04 03:51:10
Original
207 people have browsed it

How Can I Create and Manage Arrays from HTML/PHP Form Inputs?

Input as an Array in HTML/PHP Forms

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>
Copy after login

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 )
)
Copy after login

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
  )
)
Copy after login

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][]">
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template