Home >Backend Development >PHP Tutorial >HTML Forms: When Should I Use `name='something[]'` vs. `name='something'`?

HTML Forms: When Should I Use `name='something[]'` vs. `name='something'`?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-30 22:26:15742browse

HTML Forms: When Should I Use `name=

HTML Element Array: name="something[]" vs. name="something"

As noted in the documentation provided, using brackets ([]) in the name attribute of an HTML input element creates an array that can be accessed on the server-side in languages like PHP. However, in the context of HTML forms, it's important to understand the distinction between using brackets and not using them.

When an input element's name attribute does not include brackets, it represents a single value. For instance, consider the following input:

<input type="text" name="name">

When this form is submitted, the value of $_POST['name'] will be a string containing the user's input.

Now, consider the following input with brackets:

<input type="text" name="education[]">

In this case, the square brackets indicate that the input is part of an array. When the form is submitted, $_POST['education'] will be an array containing all the values entered in the inputs with the same name. For example:

$educationValues = $_POST['education']; // Returns an array
print_r($educationValues); // Shows you all the values in the array

Therefore, the brackets in the name attribute serve as a way to group related inputs into an array. This can be useful for collecting multiple values for a particular category, such as the user's education or hobbies.

However, it's important to note that HTML input elements are array-ready by name without the square brackets as well. This means that if you have multiple inputs with the same name, the browser will automatically group them into an array when the form is submitted.

<input type="text" name="education">
<input type="text" name="education">
<input type="text" name="education">

In this case, $_POST['education'] will still be an array containing the values entered in the three inputs.

The difference between using brackets and not using them primarily lies in semantic clarity. Using brackets explicitly indicates that the input is part of an array, while leaving them out can be interpreted as either a single value or an array depending on the context and the number of inputs with the same name.

The above is the detailed content of HTML Forms: When Should I Use `name='something[]'` vs. `name='something'`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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