Heres some function I made some while ago.
function formLabel($id, $text, $attr = array(), $escape = true) {
$attr['for'] = $id;
return htmlElement('label', $text, $attr, true, $escape);
}
function formSelect($name, $selected, $options, $attr = array(), $escape = true) {
$attr['name'] = $name;
if (!isset($attr['id'])) {
$attr['id'] = $name;
}
$options = formSelectOptions($selected, $options, $escape);
return htmlElement('select', $options, $attr, true, false);
}
function formSelectOptions($selected = null, $options, $escape = true) {
if ($escape) {
$options = escape($options);
}
array_walk($options, 'formSelectOption', $selected);
return implode('', $options);
}
function formSelectOption(&$value, $key, $selected) {
if (is_array($value)) {
$attr['label'] = $key;
array_walk($value, 'formSelectOption', $selected);
$value = htmlElement('optgroup', implode('', $value), $attr, true, false);
} else {
$attr['value'] = $key;
if (($selected == $key) &&
(0 === strcmp($selected, $key)) &&
($selected !== null)) {
$attr['selected'] = 'selected';
}
$value = htmlElement('option', $value, $attr, true, false);
}
}
function escape($val) {
if (is_array($val)) {
return array_map('escape', $val);
}
return htmlspecialchars($val, ENT_QUOTES);
}
function htmlElement($tag, $value, $attr = null, $end = true, $escape = true) {
if (!is_array($attr)) {
$attr = array();
}
if ($escape) {
$value = htmlspecialchars($value);
}
return "<$tag" . (!empty($attr) ? ' ' : '') . arrayToAttributes($attr) . ($end ? '' : '/') . '>' . $value . ($end ? "</$tag>" : '');
}
function arrayToAttributes($attr) {
array_walk($attr, '_arrayToAttributes');
return implode(' ', $attr);
}
function _arrayToAttributes(&$v, $k) {
$k = escape($k);
$t = escape($v);
$v = "$k=\"$t\"";
}
Some tests
<html><header><title>Test</title></header>
<body>
<p>
<?php
$arr = array('hoi', 'wee', 'hai', 'Sub' => array('Hi' => 'Hi', 'Lo' => 'Lo'));
echo '<p>', formSelect('aaaa', null, $arr), "</p>\n";
echo '<p>', formSelect('ccc', 'Hi', $arr), "</p>\n";
echo '<p>', formLabel('hello', 'Hello'), ': ', formSelect('hello', 1, $arr), "</p>\n";
?></p>
<p>
<?php
$months = array (1 => 'Januar',
'Februar', 'Mars', 'April', 'Mai',
'Juni', 'Juli', 'August', 'September',
'Oktober', 'November', 'Desember');
echo formLabel('month', 'Month'), ': ', formSelect('month', null, $months), "\n";
echo formLabel('month2', 'Month'), ': ', formSelect('month2', 4, $months), "\n";
?></p>
</body><html>