Maihan Nijat
Maihan Nijat

Reputation: 9344

How to assign HTML form multiple selected options to PHP variable?

I have HTML form with multiple select element to let the users select multiple options from the list for submission. The form method is POST and it posts the form to PHP file. I figured it out how to echo multiple selected options through out reading this How to get multiple selected values of select box in php? but I am unable to write those values to a variable as string, and having space between each option-value. Is it possible to achieve this without using array?

Here is my HTML code:

<select name="place[]" id="place" multiple>
    <optgroup label="Ottawa">
        <option value="London">London</option>
        <option value="Toronto">Toronto</option>
        <option value="Windsor">Windsor</option>
    </optgroup>
    <optgroup label="Alberta">
        <option value="Brooks">Brooks</option>
        <option value="Calgary">Calgary</option>
        <option value="Cold Lake">Cold Lake</option>
    </optgroup>
</select>

Here is the PHP code:

<?php
foreach ($_GET['place'] as $selectedOption)
    echo $selectedOption."\n";
?>

The above code only echo the values but not assigning it to variable as string. Can I simply use $locations = instead of echo?

Note: There are many Questions and Answers that shows how to assign select option value to PHP variable but not for multiple option.

Upvotes: 4

Views: 1839

Answers (1)

j08691
j08691

Reputation: 207890

Since you said you were using a post request, $_GET['place'] won't work. So using $_POST['place'] instead, you can glue the values of the array together using implode():

$locations = implode(' ', $_POST['place']);

Upvotes: 1

Related Questions