How can PHP arrays be utilized to manage multiple checkbox selections in a form?
When dealing with multiple checkbox selections in a form, PHP arrays can be utilized to manage the selected values efficiently. By setting the name attribute of the checkboxes as an array (e.g., name="checkbox[]"), PHP will automatically create an array of values corresponding to the selected checkboxes. This allows you to loop through the array and process each selected value accordingly.
<form method="post" action="process_form.php">
<input type="checkbox" name="checkbox[]" value="option1"> Option 1
<input type="checkbox" name="checkbox[]" value="option2"> Option 2
<input type="checkbox" name="checkbox[]" value="option3"> Option 3
<input type="submit" value="Submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(isset($_POST['checkbox'])){
$selectedOptions = $_POST['checkbox'];
foreach($selectedOptions as $option){
echo $option . "<br>";
}
}
}
?>