Skip to content
PHP Logo

What is the purpose of adding a checkbox in a loop in PHP?

When adding a checkbox in a loop in PHP, the purpose is typically to generate multiple checkboxes dynamically based on a set of data. This is commonly used when dealing with multiple options or items that need to be selected by the user. By using a loop, you can iterate through the data and create checkboxes for each item efficiently.

php
// Example of adding checkboxes in a loop
$items = array("Option 1", "Option 2", "Option 3");

foreach ($items as $item) {
    echo '<input type="checkbox" name="selected_items[]" value="' . $item . '">' . $item . '<br>';
}