When dealing with checkboxes, sometimes we don't know their names, such as when they are populated from the database.
So in this instance, we can actually send the checkboxes as an array in HTML, and we can loop it in PHP to access each value.
-
Send checkboxes as array in HTML
<?php foreach($result as $row): ?> <input type="checkbox" name="genre[]" value="<?= $row['genre_id'] ?>"> <label><?= $row['genre_name'] ?></label> <?php endforeach; ?>
The code above is an example of populating the checkboxes from the database. Putting [] after the name (ex. genre[]) of the checkbox will make it an array when the form is sent.
-
Access the array in PHP
for ($counter = 0; $counter < count($_POST['genre']); $counter++) { echo $_POST['genre'][$counter]; }
Using a loop in PHP, you can now access it and do whatever you need to do to it.
Conclusion
If you have dynamic checkboxes in your form, you can send them as an array in HTML by putting [] after the name of the checkbox (ex. genre[]). Then you can loop the array to access each checkbox in PHP.