Search code examples
phphtmlhtml-selectdropdownlistfor

How to store multiple values of HTML dropdownlist into array and seperate them by comma using PHP?


I want to store 4 values of this dropdownlist into an array using PHP, and I also want to separate them by comma and save them into different single variable.

<td>
    <select name="Ty" size=4 multiple>
        <option value="Action">Action</option>
        <option value="Adventure">Adventure</option>
        <option value="Animation">Animation</option>
        <option value="Bollywood">Bollywood</option>
        <option value="Marathi">Marathi</option>
        <option value="Comedy">Comedy</option>
        <option value="crime">Crime</option>
        <option value="Documentary">Documentary</option>
        <option value="Drama">Drama</option>
        <option value="Family">Family</option>
        <option value="Horror">Horror</option>
        <option value="Romance">Romance</option>
        <option value="Sci">Sci-Fi</option>
    </select>
</td> 

Solution

  • Putting values into an array

    Replace

    <select name="Ty" size=4 multiple>
    

    With

    <select name="Ty[]" size=4 multiple>
    

    Separate the values by a comma

    In the page the form points to, insert this code

    <?php
    $count = count($_POST['Ty']); //number of elements in the array
    for($i=0;$i<$count;$i++){
    $allvalues .= $_POST['Ty'][$i];
    $minus = $count-1;
    if($i<$minus){$allvalues .= ',';} //prevents to add a comma also to the last element of the array
    }
    echo $allvalues;
    ?>
    

    Saving values into different variables

    Not sure what you're exactly meaning with this. If I understood well, you could use something like this

    $var1 = $_POST['Ty'][1];