Quentin M.
Quentin M.

Reputation: 61

Storage in a variable of the options chosen in an HTML form

My question is this: I have an HTML form in which the user can select several options. I would like to retrieve all these choices and store them one after the other in a variable, separated by a comma.

I realized this:

form.html

    <select multiple class="form-control" id="motif" name="motif[]" required>
        <option>Meurtre au premier degré</option>
        <option>Meurtre au premier degré avec circ. aggr.</option>
        <option>Dissimulation de preuve</option>
        <option>Fraude</option>
    </select>

result.php

foreach ($_POST["motif"] as $valeur) {
    $selecteditem = $selecteditem+$valeur;
}
echo $selecteditem;

output 'echo $selecteditem'

0

I don't understand this "0", I would like a result like: "Corruption, Armed robbery, Illegal carrying of weapons" at the output of the variable $selecteditem

Thank you for your expert advice :)

Upvotes: 0

Views: 68

Answers (1)

Yusuf Moola
Yusuf Moola

Reputation: 178

Add values to your options, so make it:

<select multiple class="form-control" id="motif" name="motif[]" required>
    <option value='degre'>Meurtre au premier degré</option>
    <option value='circ'>Meurtre au premier degré avec circ. aggr.</option>
    <option value='preuve'>Dissimulation de preuve</option>
    <option value='fraude'>Fraude</option>
</select>

Then change your php to:

$selectedItems = join(', ', $_POST["motif"]);

This will take the array and join it using comma as the glue.

Upvotes: 1

Related Questions