rendra
rendra

Reputation: 341

Is it safe to send input type checkbox using double bracket [] in the name attribute?

Some of tutorial show me to use checkbox with double bracket so the value can retrieved as array, but some of tutorial is not.

<input type='checkbox' name='hobby[]' value='reading'> Reading

Which one standart? And is it actually safe to send input type checkbox using double bracket [] in the name attribute?

Upvotes: 1

Views: 894

Answers (1)

Andrew Surzhynskyi
Andrew Surzhynskyi

Reputation: 2776

The only purpose of this approach is to use multi-dimentional $_GET array in PHP (and probably some other server-side languages).

Approach №1: No brackets

The way how we use it most of the time. Provided so you can see the difference between this approach and two others.

<label>
    <input type="checkbox" name="hobby_reading" value="1" /> Reading
</label>

<label>
    <input type="checkbox" name="hobby_programming" value="1" /> Programming
</label>

var_dump($_GET) output:

array(2) {
    ["hobby_reading"] => string(1) "1"
    ["hobby_programming"] => string(1) "1"
}

Approach №2: Names in brackets

Provides us a nested associative hobby array as a member of $_GET array.

<label>
    <input type="checkbox" name="hobby[reading]" value="1" /> Reading
</label>

<label>
    <input type="checkbox" name="hobby[programming]" value="1" /> Programming
</label>

var_dump($_GET) output:

array(1) {
    ["hobby"] => array(2) {
        ["reading"] => string(1) "1"
        ["programming"] => string(1) "1"
    }
}

Approach №3: Double brackets

Provides us a nested non-associative hobby array as a member of $_GET array.

<label>
    <input type="checkbox" name="hobby[]" value="reading" /> Reading
</label>

<label>
    <input type="checkbox" name="hobby[]" value="programming" /> Programming
</label>

var_dump($_GET) output:

array(1) {
    ["hobby"] => array(2) {
        [0] => string(7) "reading"
        [1] => string(11) "programming"
    }
}

Answering your question

Yes. It is safe to use this approach, but you can face some problems when trying to get inputs DOM elements by name with vanilla JavaScript or jQuery (here is how to solve the problem for jQuery: jQuery selector for inputs with square brackets in the name attribute)

Upvotes: 2

Related Questions