Sarmad Nazir
Sarmad Nazir

Reputation: 23

HTML Multiple options Select Box Multiple Times on same name

Actually I am working on Education Management System but I am stuck on it.

<select name="teachers[]"  multiple="multiple"  class="chosen-select input-xlarge">
        <option value="1">option1</option>
        <option value="2">option2</option>  
    </select>

    <select name="teachers[]"  multiple="multiple"  class="chosen-select input-xlarge">
        <option value="1">option1</option>
        <option value="2">option2</option>  
    </select>

I am using it multiples time but after submission the output look like this

[teachers] => Array
    (
       [0] => 1
       [1] => 2
       [2] => 1
       [3] => 2
    )

But i need output like this

[teachers] => Array
        (
            [0] => Array
                (
                    [0] => 1
                    [1] => 2
                )

        [1] => Array
            (
                [0] => 1
                [1] => 2
            )
     )

Upvotes: 1

Views: 1186

Answers (1)

kero
kero

Reputation: 10638

You can achieve this by using a multidimensional array in the form and setting a fixed value for the first dimension.

<select name="teachers[0][]"  multiple="multiple"  class="chosen-select input-xlarge">
    <option value="1">option1</option>
    <option value="2">option2</option>  
</select>

<select name="teachers[1][]"  multiple="multiple"  class="chosen-select input-xlarge">
    <option value="1">option1</option>
    <option value="2">option2</option>  
</select>

The concept behind x[] is: Make x an array and add each selected value to it. So by using x[0][] in the first case it becomes: Make x[0] an array and add each selected value to it. In the second case it is: Make x[1] an array and add the selected values to it - resulting in the desired output.

However, if you used x[][], this would result in every selected item being its own array, as for each item, a new array will be created.

Upvotes: 4

Related Questions