How to access checkboxes with unknown names in PHP?

Last Updated on Mar 24, 2024

checkboxes of genre

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.

  1. 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.

  2. 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.

© John Michael Balbarona