How can PHP code be modified to display all selected checkbox options, rather than just the last one?

When handling multiple selected checkbox options in PHP, the issue typically arises because the same name attribute is used for all checkboxes. As a result, only the last selected checkbox option is displayed. To display all selected checkbox options, you can modify the name attribute to an array format by adding "[]" at the end of the name attribute. This way, PHP will treat the selected options as an array and you can loop through them to display all selected options.

<form method="post">
    <input type="checkbox" name="colors[]" value="red"> Red<br>
    <input type="checkbox" name="colors[]" value="blue"> Blue<br>
    <input type="checkbox" name="colors[]" value="green"> Green<br>
    <input type="submit" value="Submit">
</form>

<?php
if(isset($_POST['colors'])) {
    foreach($_POST['colors'] as $color) {
        echo $color . "<br>";
    }
}
?>