John Smith
John Smith

Reputation: 359

How can I make the output of this form input an array?

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?

Upvotes: 4

Views: 87

Answers (3)

user1937699
user1937699

Reputation:

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

<select name='tag[]' multiple>

For PHP side :

foreach ($_POST['tag'] as $selectedOption){
    echo $selectedOption."\n";
}

Upvotes: 13

aarju mishra
aarju mishra

Reputation: 710

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

Upvotes: 0

suman das
suman das

Reputation: 367

<select name='tag[]' multiple>

Upvotes: 0

Related Questions