What are the best practices for structuring PHP functions to generate form elements dynamically?

When generating form elements dynamically in PHP, it is important to structure your functions in a way that allows for flexibility and reusability. One common approach is to create a function that takes in parameters such as element type, name, value, and additional attributes, and then generates the corresponding HTML code for the form element. This allows you to easily create different types of form elements with varying attributes without having to duplicate code.

function generateFormElement($type, $name, $value = '', $attributes = array()) {
    $html = '<input type="' . $type . '" name="' . $name . '" value="' . $value . '"';
    
    foreach ($attributes as $key => $val) {
        $html .= ' ' . $key . '="' . $val . '"';
    }
    
    $html .= '>';
    
    return $html;
}

// Example usage
echo generateFormElement('text', 'username', '', array('placeholder' => 'Enter your username', 'required' => 'required'));