How can I output this form to an array?

I am trying to create a form in which users can select several options from a dropdown menu. This form looks something like this:

<html>

<form method='post'>
<select name='tag' multiple>
<option value='opt1'>Option 1</option>
<option value='opt2'>Option 2</option>
<option value='opt3'>Option 3</option>
<option value='opt4'>Option 4</option>
<option value='opt5'>Option 5</option>
</select>
<input type='submit' Value='Submit'>
</form>

<? include('select.php'); ?>

</html>

If the php file contains the following simple code:

<?php

if($_POST){

$tag = $_POST['tag'];
echo $tag;

}

?>

The end result of this code is a drop-down menu from which you can select several options. However, when you click the Submit button, it selects only one of the options selected by the user.

How can I create an array of all parameters selected by the user?

+4
source share
3 answers

Try Change to <select name='tag' multiple>to

<select name='tag[]' multiple>

For the PHP side:

foreach ($_POST['tag'] as $selectedOption){
    echo $selectedOption."\n";
}
+13
source
<select name='tag[]' multiple>
0
source

select :

<select name='tag[]' multiple>

PHP:

foreach ($_POST['tag'] as $option_selected){
    echo $option_selected;
}
0

All Articles