Skip to content

Instantly share code, notes, and snippets.

@finalwebsites
Created March 29, 2016 05:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save finalwebsites/40e7f5554d3de7225c6b to your computer and use it in GitHub Desktop.
Save finalwebsites/40e7f5554d3de7225c6b to your computer and use it in GitHub Desktop.
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