Get multiple values from a multi select

3

I need to get values from a multiselect

<select id="opcoes" name="opcoes[]" class="select" multiple="multiple" size="5" data-required required="required">
<option value="opcao1">Opção 1</option>
<option  value="opcao2">Opção 2</option>
<option  value="opcao3">Opção 3</option>

I would like to know how I can get the selected values and put them in a php variable.

I've tried with $_POST['opcoes[]'] , but it always returns null for me.

    
asked by anonymous 03.11.2015 / 13:35

2 answers

4

To call all selected options just $_POST['opcoes'] , select name must have brackets, and the multiple attribute to work correctly.

<form method="post" action="#">
   <select id="opcoes" name="opcoes[]" multiple="multiple" >
      <option value="opcao1">Opção 1</option>
      <option  value="opcao2">Opção 2</option>
      <option  value="opcao3">Opção 3</option>
   </select>

   <input type="submit" />
</form>

<?php
   foreach($_POST['opcoes'] as $item){
      echo $item .'<br>';   
   }

In the production code, do not forget to check if there are marked items, you can use the count() function to avoid sending a null in the foreach.

    
03.11.2015 / 13:50
2

You do not need to [] .

Example working:

  

HTML

 <form method="POST" action="../../model/php/teste.php" >
    <select id="opcoes" name="opcoes[]" class="select" multiple="multiple" size="5" data-required required="required">
       <option value="opcao1">Opção 1</option>
       <option  value="opcao2">Opção 2</option>
       <option  value="opcao3">Opção 3</option>
    </select>
    <button type="submit">Enviar</button>
 </form>
  

PHP

var_dump($_POST['opcoes']);
    
03.11.2015 / 13:52