Question

I have a drop down menu that I want to change to a multiple select box. The code below is working if you only select 1 option (the way I had it before), but of you select 2 it will only show 1 of the two, how can I make it show both options selected, here is the code:

<?php $makes = array("volvo","Saab","Opel","Audi","BMW") ?>


<form method="post" name="store" action="<?php $_SERVER['PHP_SELF'] ?>" >
<select multiple="multiple" name="cars">
<?php foreach ($makes as $make){echo "<option value=\"$make\">". $make ."</option>";           $vehicles = $_POST['cars'];} ?>
    <input name="submit" type="submit">
    </select>
</form>
<?php 


if($_POST['submit']){
  echo $vehicles;
}
?>
</body>
</html>
Was it helpful?

Solution 2

It isn't completely clear from your question but I think you mean the following bit of code only echoes one value:

if($_POST['submit']){
  echo $vehicles;
}

To turn your selected cars into an array you need to add [] onto the end of the name:

<select multiple="multiple" name="cars[]">

Then to echo each of the selections you can use a foreach loop:

foreach ($_POST['cars'] as $car)
    echo $car.'<br />';

OTHER TIPS

I hope I read this correctly that you would like to retrieve an array of results from the HTML multi select box.

By the way your code snippit is not correct; the HTML <form> closing tag should be after your closing <select> tag and I'm not sure why you have the following in your PHP for() loop:

$vehicles = $_POST['cars'];

You will want to make the HTML tags' name attribute an array as follows (Note I did not test this code):

<select multiple="multiple" name="cars[]">
<?php 
    foreach ($makes as $make) {
        echo "<option value=\"$make\">". $make ."</option>";
    }
?>
</select>

<?php 
    if($_POST['submit']) {
        print_r($_POST['cars']);
     }
?>

PHP.net - How do I get all the results from a select multiple HTML tag?

you can try with if($_POST['submit']){ print_r($vehicles); } please let me know if any issue then..

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top