Generate A Radio Button Group With PHP

1st January 2008

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.
  1. function createRadio($name,$options,$default=''){
  2. $name = htmlentities($name);
  3. $html = '';
  4. foreach($options as $value=>$label){
  5. $value = htmlentities($value);
  6. $html .= '<input type="radio" ';
  7. if($value == $default){
  8. $html .= ' checked="checked" ';
  9. };
  10. $html .= ' name="'.$name.'" value="'.$value.'" />'.$label.'<br />'."\n";
  11. };
  12. return $html;
  13. }

You can call the function in the following way:

  1. $array = array('one'=>'One',
  2. 'two'=>'Two',
  3. 'three'=>'Three',
  4. 'four'=>'Four');
  5. echo createRadio('numbers',$array,'three');

Which produces the following output:

  1. <input type="radio" name="numbers" value="one" />One<br />
  2. <input type="radio" name="numbers" value="two" />Two<br />
  3. <input type="radio" checked="checked" name="numbers" value="three" />Three<br />
  4. <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.