Take multiple values from a multi select

Asked

Viewed 1,787 times

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 wonder how I can take the selected values and put in a php variable.

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

2 answers

4


To call all selected options just do $_POST['opcoes'], select name must have brackets and attribute multiple to function properly.

<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 make a check if there are marked items, you can use the function count() to avoid sending a null in the foreach.

2

You don’t have to put [].

Working example:

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']);
  • I don’t get it, you need the colchetes? in the answer says no but in the code they are :)

  • @rray In the answer he refers to what he has tried as $_POST['opcoes[]'] but actually there is no need for the use, being that $_POST['opcoes'] would already return the array.

  • Aaaaaah that brackets hehe, now I get it.

  • rray and Gabriel Rodrigues, obg for the help. They clarified what I needed. I used the brackets because I thought that when I picked more than one option in select, I would be working with an array, so I put it (I had also searched this and some search sources indicated the use of the bracket). vlw guys!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.