Home > Backend Development > PHP Tutorial > How to Retrieve Multiple Selected Values from a Multi-Select HTML Form in PHP?

How to Retrieve Multiple Selected Values from a Multi-Select HTML Form in PHP?

Mary-Kate Olsen
Release: 2024-12-18 07:00:12
Original
997 people have browsed it

How to Retrieve Multiple Selected Values from a Multi-Select HTML Form in PHP?

Retrieving Multiple Selected Values from a Select Box in PHP

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>
Copy after login

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 ...>
Copy after login

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";
}
?>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template