Home >Backend Development >PHP Tutorial >How to Retrieve Multiple Selected Values from a Select Box in PHP using GET?

How to Retrieve Multiple Selected Values from a Select Box in PHP using GET?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-19 20:09:11673browse

How to Retrieve Multiple Selected Values from a Select Box in PHP using GET?

Retrieving Multiple Selected Values from a Select Box in PHP

When creating a form with a select box that allows multiple selections, it becomes necessary to access the selected values on the server-side. This article demonstrates how to retrieve these values in PHP when the form uses the GET method.

Form Structure

The following HTML code represents a form with a select box named "select2" that has the "multiple" attribute set, allowing users to choose multiple options:

<form>

Accessing Selected Values in PHP

To retrieve the selected values in PHP, we can use the $_GET superglobal array:

// Use $_GET or $_POST depending on the form method
$selectedOptions = isset($_GET['select2']) ? $_GET['select2'] : [];

foreach ($selectedOptions as $option) {
  // Do something with the selected option (e.g., print it)
  echo $option . "\n";
}

Key to Retrieval

In the PHP code above, we add square brackets to the name of the select element: select2[]. This informs PHP that the element should be treated as an array of options. When the form is submitted, the selected values will be stored in the $_GET['select2'] array.

Conclusion

By understanding how to access the selected values of a multiple-selection select box in PHP, you can effectively collect user input and store it on the server-side for further processing.

The above is the detailed content of How to Retrieve Multiple Selected Values from a Select Box in PHP using GET?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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