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[]">
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>'; } ?>
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>'; } ?>
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 }
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!