Is it recommended to create a function in PHP to handle the generation of HTML select boxes with pre-selected values for better code organization and reusability?

It is recommended to create a function in PHP to handle the generation of HTML select boxes with pre-selected values for better code organization and reusability. This approach allows you to centralize the logic for generating select boxes with pre-selected options, making it easier to maintain and reuse the code in different parts of your application.

<?php
function generateSelectBox($name, $options, $selectedValue) {
    $selectBox = '<select name="' . $name . '">';
    foreach($options as $value => $label) {
        $selected = ($value == $selectedValue) ? 'selected' : '';
        $selectBox .= '<option value="' . $value . '" ' . $selected . '>' . $label . '</option>';
    }
    $selectBox .= '</select>';
    
    return $selectBox;
}

// Example usage
$options = [
    '1' => 'Option 1',
    '2' => 'Option 2',
    '3' => 'Option 3'
];
$selectedValue = '2';

echo generateSelectBox('mySelect', $options, $selectedValue);
?>