Home >Backend Development >PHP Tutorial >How to Retrieve Multiple Checkbox Values on Form Submission?

How to Retrieve Multiple Checkbox Values on Form Submission?

Barbara Streisand
Barbara StreisandOriginal
2024-12-09 06:01:09710browse

How to Retrieve Multiple Checkbox Values on Form Submission?

Retrieving Checkboxes Values on Form Submission

In this scenario, you have multiple checkbox options and need to capture their checked values when the form is submitted. Here's how to approach it:

The HTML form defines the checkbox options and generates the $_GET array when submitted. Each checkbox has a name attribute (color[]) and a value attribute representing the selected color.

In your third.php script, you can access the checked values using the $_GET array. However, since there are multiple checkboxes with the same name (color[]), the values will be stored as an array in $_GET['color'].

To retrieve the values, use a foreach loop to iterate through the array. For each checkbox that was checked, its value will be printed.

Example Code:

HTML Form:

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

third.php Script:

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

// Optional: Output message to confirm checked values
echo "You chose the following color(s):<br>";

foreach ($color as $selectedColor) {
    echo $selectedColor . "<br>";
}

?>

Using this approach, you can successfully retrieve the checked values from your checkbox form inputs and store them for further processing as needed.

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