What potential pitfalls can arise from using the same name for multiple checkboxes in a loop in PHP?
Using the same name for multiple checkboxes in a loop in PHP can cause issues with processing the form data correctly. To solve this problem, you can append square brackets `[]` to the checkbox name to create an array of values for that input field. This way, you can easily loop through the array to access each checkbox value individually.
<form method="post">
<?php
$checkboxes = ['option1', 'option2', 'option3'];
foreach ($checkboxes as $checkbox) {
echo '<input type="checkbox" name="checkboxes[]" value="' . $checkbox . '">' . $checkbox . '<br>';
}
?>
<input type="submit" name="submit" value="Submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST['checkboxes'])) {
foreach ($_POST['checkboxes'] as $checkbox) {
echo $checkbox . ' is selected.<br>';
}
}
}
?>