Create a gist now

Instantly share code, notes, and snippets.

Create a radio group with PHP
<?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');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment