Here is a function to create a group of radio buttons in a HTML form. The three parameters are:
- $name : The name of the radio group.
- $options : An associative array of items to be included in the group of radio buttons.
- $default : The default value of the radio buttons.
function createRadio($name,$options,$default=''){
$name = htmlentities($name);
$html = '';
foreach($options as $value=>$label){
$value = htmlentities($value);
$html .= '<input type="radio" ';
if($value == $default){
$html .= ' checked="checked" ';
};
$html .= ' name="'.$name.'" value="'.$value.'" />'.$label.'<br />'."\n";
};
return $html;
}
You can call the function in the following way:
$array = array('one'=>'One',
'two'=>'Two',
'three'=>'Three',
'four'=>'Four');
echo createRadio('numbers',$array,'three');
Which produces the following output:
<input type="radio" name="numbers" value="one" />One<br />
<input type="radio" name="numbers" value="two" />Two<br />
<input type="radio" checked="checked" name="numbers" value="three" />Three<br />
<input type="radio" name="numbers" value="four" />Four<br />