How can PHP and HTML be effectively combined to avoid surprises when creating form elements like SELECT?

When combining PHP and HTML to create form elements like SELECT, it is important to ensure that the PHP code generates the options dynamically based on data from a database or other source. This helps avoid surprises such as outdated or incorrect options being displayed. By dynamically generating the options with PHP, you can ensure that the SELECT element is always up-to-date and accurate.

<select name="category">
    <?php
    // Assume $categories is an array of category options fetched from a database
    foreach ($categories as $category) {
        echo "<option value='" . $category['id'] . "'>" . $category['name'] . "</option>";
    }
    ?>
</select>