Home > database >  Get multiple input fields value with same name but in different arrays in PHP
Get multiple input fields value with same name but in different arrays in PHP

Time:11-10

I am trying to get the values of multiple input fields with the same name as an array. But the scenario is one of the field is multi-select and it itself has multiple values. I want these to get multiple selected values in different arrays. What I mean to say if I select 2 values in multi-select 1 and 3 values in multi-select 2.

I should get the values like

array(
  [0] => array(
    [0] => value 1
    [1] => value 2
  [1] => array(
    [0] => value 3
    [1] => value 4
    [5] => value 5
     )
  )
)

But right now I am getting the values like

array(
[0] => value 1
[1] => value 2
[2] => value 3
[3] => value 4
[4] => value 5
)

Here is my code

View.php

      <label for="dependent_benefit"><?php echo "Benefit Name" ?></label>
    <select name="dependent_benefit[]" id="dependent_benefit" class="form-control" multiple="multiple">
    <?php
    foreach ($benefitlist as $list) { ?>
    <option value="<?php echo $list->benefit_id ?>"><?php echo $list->benefit_name ?></option>
    <?php }
    ?>
    </select>
   <label for="dependent_benefit"><?php echo "Benefit Name" ?></label>
    <select name="dependent_benefit[]" id="dependent_benefit" class="form-control" multiple="multiple">
    <?php
    foreach ($benefitlist as $list) { ?>
    <option value="<?php echo $list->benefit_id ?>"><?php echo $list->benefit_name ?></option>
    <?php }
    ?>
    </select>

After form submit Controller.php

$dependent_benefit = $this->input->post('dependent_benefit', true);

CodePudding user response:

Add a number to your form input name for the position of the array where you want it to go.

<select name="dependent_benefit[0][]" id="dependent_benefit" class="form-control" multiple="multiple">
<select name="dependent_benefit[1][]" id="dependent_benefit" class="form-control" multiple="multiple">

CodePudding user response:

Just use 2d array with offset like:

<select name="dependent_benefit[0][]" id="dependent_benefit" class="form-control" multiple="multiple">
<select name="dependent_benefit[1][]" id="dependent_benefit" class="form-control" multiple="multiple">
  • Related