A php function to create a group of HTML radio elements


Dynamic radio group (HTML) ver. 1.00

released: 2007-06-26
Creating radio elements in some content management systems can result into writing a lot of code. Just in case your radio group with multiple options is getting a value from a database and/or a form. There need to be a check for every posted value for every option. This function will do all this work for you, just create two arrays, one for the values and labels and for the related html code. It's up to the user if he uses 2 or more elements in one group. The function works with $_POST and $_GET data.

Viewed 10752 times

Rating: script rated with stars
 

Your banner at finalwebsites.com?
use the contact form for further information and prices.

<?php
$values = array('google'=>'Google Search', 'link'=>'Link on some website', 'advert'=>'Advertisement', 'news'=>'News');
$html_elements = array('before'=>'<span>', 'after'=>'</span><br />', 'label'=>'<label for="test"><b>Some label</b></label><br />');

function dynamic_radio_group($formelement, $values, $html, $def_value = '') {
    $radio_group = '<div>'."\n";
    $radio_group .= (!empty($html['label'])) ? $html['label']."\n" : '';
   
    if (isset($_REQUEST[$formelement])) {
        $curr_val = stripslashes($_REQUEST[$formelement]);
    } elseif (isset($def_value) && !isset($_REQUEST[$formelement])) {
        $curr_val = $def_value;
    } else {
        $curr_val = "";
    }
    foreach ($values as $key => $val) {
        $radio_group .= $html['before']."\n";
        $radio_group .= '<input name="'.$formelement.'" type="radio" value="'.$key.'"';
        $radio_group .= ($curr_val == $key) ? ' checked="checked" />' : ' />';
        $radio_group .= ' '.$val."\n".$html['after']."\n";
    }
    $radio_group .= '</div>'."\n";
    return $radio_group;      
}

// place this code between the form tags:
// notice 'advert' could be a database value too
echo dynamic_radio_group('test', $values, $html_elements, 'advert');
?>