4

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.

4
  • If "The form method is POST and it posts the form to PHP file" then why are you using $_GET['place'] ? And since you want to convert an array into a string, why aren't you just using implode()? Commented Jan 17, 2016 at 20:07
  • @j08691 I have no problem using implode() as I am new to PHP and struggling with methods. What will be the correct statement in that case? Commented Jan 17, 2016 at 20:12
  • 1
    $locations = implode(' ', $_POST['place']) Commented Jan 17, 2016 at 20:18
  • @j08691 Thanks. It worked. Commented Jan 17, 2016 at 20:20

1 Answer 1

1

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']);
Sign up to request clarification or add additional context in comments.

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.