This code is part of my Code Grimoire.

<?php
/*
 * formhelper.php by Felix Pleșoianu <felixp7@yahoo.com>
 * Functions to generate repeating form fields.
 *
 * If you are asking what license this software is released under,
 * you are asking the wrong question.
 */

function html_options($data, $defaults = array()) {
    $tpl = '<option value="%s">%s</option>' . "\n";
    $tpl_sel = '<option value="%s" selected="selected">%s</option>' . "\n";
    if (!is_array($defaults)) $defaults = array($defaults);
    $output = '';
    foreach ($data as $value => $label) {
        if (in_array($value, $defaults))
            $output .= sprintf($tpl_sel, $value, $label);
        else
            $output .= sprintf($tpl, $value, $label);
    }
    return $output;
}

function html_checkboxes($name, $data, $defaults = array()) {
    $tpl = '<label><input type="checkbox" name="%s[]" value="%s">'
        . ' %s</label>' . "\n";
    $tpl_sel = '<label><input type="checkbox" name="%s[]" value="%s"'
        . ' checked="checked"> %s</label>' . "\n";
    if (!is_array($defaults)) $defaults = array($defaults);
    $output = '';
    foreach ($data as $value => $label) {
        if (in_array($value, $defaults))
            $output .= sprintf($tpl_sel, $name, $value, $label);
        else
            $output .= sprintf($tpl, $name, $value, $label);
    }
    return $output;
}

function html_radios($name, $data, $default = null) {
    $tpl = '<label><input type="radio" name="%s" value="%s">'
        . ' %s</label>' . "\n";
    $tpl_sel = '<label><input type="radio" name="%s" value="%s"'
        . ' checked="checked"> %s</label>' . "\n";
    //if (!is_array($defaults)) $defaults = array($defaults);
    $output = '';
    foreach ($data as $value => $label) {
        if ($value == $default)
            $output .= sprintf($tpl_sel, $name, $value, $label);
        else
            $output .= sprintf($tpl, $name, $value, $label);
    }
    return $output;
}
?>
Last modified: Tue 04 05 2010, 12:30:40 UTC