How can the use of optgroup in HTML be optimized for creating dynamic selection boxes in PHP?

When creating dynamic selection boxes in PHP using optgroup in HTML, it's important to generate the optgroup elements dynamically based on the data retrieved from the database. This can be achieved by iterating through the data and creating optgroup elements for each distinct category or group. By dynamically generating the optgroup elements, the selection box can be optimized for displaying a large amount of data in a structured and organized manner.

<select name="dynamic_select">
    <?php
    // Assume $data is an array of data retrieved from the database
    $categories = array_unique(array_column($data, 'category'));

    foreach ($categories as $category) {
        echo '<optgroup label="' . $category . '">';
        
        foreach ($data as $item) {
            if ($item['category'] == $category) {
                echo '<option value="' . $item['id'] . '">' . $item['name'] . '</option>';
            }
        }
        
        echo '</optgroup>';
    }
    ?>
</select>