Monday, April 18, 2011

multiple listbox select to get a comma separated value

So you have a list box with multiple selects and you want to get a commma separated value of selected values when the form is submited
It is simple html and some php.

example code:
<form action="" method="POST">
<select multiple name="mypets[]">
    <option value="dog">Dog</option>
    <option value="cat">Cat</option>
    <option value="bird">Bird</option>
    <option value="mouse">Mouse</option>
</select>

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

<?php

$mypets = isset($_POST['mypets'])? $_POST['mypets'] : array();
$pets_csv = implode(',',$mypets);

echo($pets_csv);
?>


explantion:
not there that he emphasis is on the "[]" put on front of the name of the list box
thus we are naming it "mypets[]" instead of say "mypets" so that values are stored in the post variable as and array
The as usually you can use implode to get the comma separated values accordingly.
Hope this helps someone who especially overlooks to add "[]" to the name.

No comments:

Post a Comment