4

I'm trying to create a form in which users can select multiple options from a drop down menu. This form looks something like the following:

<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>

Where 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 may select multiple options. However, when you click submit, it only echos one of the options that the user selected.

How can I make an array of all of the options selected by the user?

3 Answers 3

13

Try Changes the to <select name='tag' multiple> to

<select name='tag[]' multiple>

For PHP side :

foreach ($_POST['tag'] as $selectedOption){
    echo $selectedOption."\n";
}
Sign up to request clarification or add additional context in comments.

Comments

0
<select name='tag[]' multiple>

1 Comment

While this code block may answer the question, it would be best if you could provide a little explanation for why it does so.
0

You can change your select tag from this to this:

<select name='tag[]' multiple>

In PHP:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.