9

I have this HTML code :

<select name="cars">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>

and to make user able to select more than one items, I'm using this jQuery plugin : http://harvesthq.github.com/chosen/

but, once it submitted... the PHP script only able to retrieve one of $_POST['cars'] value. the last one. how to make PHP to be able to retrieve ALL of it?

jww
  • 97,681
  • 90
  • 411
  • 885
Saint Robson
  • 5,475
  • 18
  • 71
  • 118

2 Answers2

34

I've found the answer...

<select name="cars[]" multiple="multiple">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>

and in the PHP part :

$cars = $_POST['cars'];
print_r ($cars);
mezoid
  • 28,090
  • 37
  • 107
  • 148
Saint Robson
  • 5,475
  • 18
  • 71
  • 118
  • 4
    Just to clarify. In HTML, you need to make sure the name attribute is an array, which you do by adding `[]` at the end of the name. As this example shows. – Joshua Pack Apr 09 '15 at 20:48
  • 2
    Just to clarify even more. This is a PHP trick that has nothing to do with the HTML/DOM spec. – dotnetCarpenter Jan 10 '17 at 20:10
0

you must do the following:

//$_POST or $_GET is the method of your form request

foreach ($_POST['cars'] as $selected_option) {
    echo $selected_option;
}

that's it.

Alaa M. Jaddou
  • 1,180
  • 1
  • 11
  • 30