Generate A Radio Button Group With PHP

Here is a function to create a group of radio buttons in a HTML form. The three parameters are:

  1. $name : The name of the radio group.
  2. $options : An associative array of items to be included in the group of radio buttons.
  3. $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 />

 

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
1 + 0 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.