Home > Backend Development > PHP Tutorial > How to Retrieve Selected Checkbox Values in PHP After Form Submission?

How to Retrieve Selected Checkbox Values in PHP After Form Submission?

Linda Hamilton
Release: 2024-12-01 18:43:11
Original
306 people have browsed it

How to Retrieve Selected Checkbox Values in PHP After Form Submission?

Retrieving Checkbox Selections on Form Submission

When handling checkbox inputs in a form, the challenge arises in retrieving the checked values to store them for further processing. This article provides a comprehensive guide on capturing checkbox selections for use in PHP.

Firstly, the HTML form should include checkbox inputs with appropriate values assigned. Consider the following example:

<form action="third.php" method="get">
    <!-- Choices -->
    Red     <input type="checkbox" name="color[]">
Copy after login

On the PHP handling page (third.php), retrieving the selected checkbox values can be achieved using $_GET or $_POST, depending on the method attribute in the HTML form. Let's examine both methods:

Using $_GET

<?php
$color = $_GET['color'];

foreach ($color as $selected) {
    echo 'The checked color is: ' . $selected . '<br>';
}
?>
Copy after login

In this example, $color is an array containing the values of the checked checkboxes. The foreach loop iterates through the array, printing each selected color on a new line.

Using $_POST

Implement the same approach using $_POST:

<?php
$color = $_POST['color'];

foreach ($color as $selected) {
    echo 'The checked color is: ' . $selected . '<br>';
}
?>
Copy after login

Remember to ensure that the form's method attribute matches the handling method used (get or post) for the script to function correctly.

Additionally, you can employ error handling to verify whether any checkbox was selected using isset().

if (isset($_GET['color'])) {
    // Checkbox was selected
} else {
    // Display an error message
}
Copy after login

The above is the detailed content of How to Retrieve Selected Checkbox Values in PHP After Form Submission?. 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