When constructing HTML forms with a select box that allows multiple selections, it's often necessary to retrieve the chosen values in the subsequent PHP script. This article provides a detailed solution for accessing and displaying the selected options from a multi-select box.
Consider the following HTML form:
<form method="get" action="display.php"> <select name="select2[]" multiple size="3"> <option value="11">eleven</option> <option value="12">twelve</option> <option value="13">thirette</option> <option value="14">fourteen</option> <option value="15">fifteen</option> </select> <input type="submit" name="Submit" value="Submit"> </form>
To retrieve the selected values in display.php, it's essential to add square brackets [] to the name attribute of the select box:
<select name="select2[]" multiple ...>
This informs PHP to treat $_GET['select2'] as an array. Accessing the array in display.php becomes straightforward:
<?php header("Content-Type: text/plain"); foreach ($_GET['select2'] as $selectedOption) { echo $selectedOption . "\n"; } ?>
By looping through the $_GET['select2'] array, you can retrieve and display each selected value.
The above is the detailed content of How to Retrieve Multiple Selected Values from a Multi-Select HTML Form in PHP?. For more information, please follow other related articles on the PHP Chinese website!