Skip to content
PHP Logo

How can loops be effectively utilized to streamline the display of checkbox inputs in PHP forms?

When dealing with a large number of checkbox inputs in PHP forms, using loops can greatly streamline the process of displaying and handling them. By dynamically generating the checkboxes using a loop, you can avoid repetitive code and easily manage the inputs. This approach also allows for easier scalability if the number of checkboxes needs to be adjusted in the future.

php
<form method="post">
<?php
$checkboxes = array("Option 1", "Option 2", "Option 3", "Option 4");

foreach ($checkboxes as $checkbox) {
    echo '<input type="checkbox" name="options[]" value="' . $checkbox . '">' . $checkbox . '<br>';
}
?>
<input type="submit" value="Submit">
</form>