Bruno Reis Silvino
Bruno Reis Silvino

Reputation: 39

How can get values from select-inputs with the same name using php method POST?

I'm trying to do something like this:

HTML

<form action="" method="post">

 <input type="hidden" name="id[]">
 <select name="type[]">
   <option value="0">Option 0</option>
   <option value="1">Option 1</option>
 </select>

 <input type="hidden" name="id[]">
 <select name="type[]">
   <option value="0">Option 0</option>
   <option value="1">Option 1</option>
 </select>

 <input type="hidden" name="id[]">
 <select name="type[]">
   <option value="0">Option 0</option>
   <option value="1">Option 1</option>
 </select>
</form>

PHP

<?php
 for ($i=0; $i < sizeof($_POST['id']) ; $i++) {
  $id[$i] = $_POST['type'][$i];
  echo $id[$i];
 } 
?>

But all can I get is the first select-input value. How can I get the others?

Upvotes: 0

Views: 731

Answers (1)

Ikishie
Ikishie

Reputation: 46

<form action="#" method="post">

<input type="hidden" name="id[]">
<select name="type[]">
  <option value="0">Option 0</option>
  <option value="1">Option 1</option>
</select>

<input type="hidden" name="id[]">
<select name="type[]">
  <option value="0">Option 0</option>
  <option value="1">Option 1</option>
</select>

<input type="hidden" name="id[]">
<select name="type[]">
  <option value="0">Option 0</option>
  <option value="1">Option 1</option>
</select>

<!-- Add a sumbmit button -->
<input type="submit" value="Go">
</form>

PHP Code :

<?php
  if(!empty($_POST)){

  for ($i=0; $i < count($_POST['id']) ; $i++) {
     $id[$i] = $_POST['type'][$i];
  }
  print_r($id);
  /* 
  Return : Array ( [0] => 0 [1] => 1 [2] => 1 )
  */
}
?>

Upvotes: 1

Related Questions