How to Get HTML Multi-Select Values in PHP?

Reading HTML multi-select values in a PHP server-side script

To get all selected values of a <select multiple> HTML element (when submitted via post for example, to a PHP script on the server-side), you need make sure the name attribute of the <select> element ends with square brackets ([]). When you do that, PHP is able to pick up the values as an array on the server-side, accessible via its superglobal arrays.

For example, suppose you have the following multi-select HTML element:

<form action="fav-music.php" method="post">
    <select multiple name="genres[]">
        <option value="rock" selected>Rock</option>
        <option value="pop" selected>Pop</option>
        <option value="country">Country</option>
        <option value="hip-hop">Hip-Hop</option>
        <!-- ... -->
    </select>

    <input type="submit" />
</form>

When the form is submitted, you would read the selected values submitted to the server-side PHP script, for example, in the following way:

<?php
// fav-music.php

$values = $_POST['genres']; // e.g. ['Rock', 'Pop']

foreach ($values as $value) {
    echo $value;
}

Hope you found this post useful. It was published . Please show your love and support by sharing this post.