Handy PHP
TalkPHP
Get friendly help with your PHP problems for free.
www.talkphp.com
The PHP Resource Index

Refer A Friend using Revolution Money Exchange
Wordtracker Keyword Research
Build Select Field PDF Print E-mail
Written by Handy PHP Administrator   
Saturday, 21 October 2006 05:00
Description:
  string build_select_field(string name, array selections, string selected[, string options[, string prepemd[, string prepend[, string append[, string indent]]]]])
     
  This handy PHP function will reduce the amount of typing you do when you are designing HTML forms.  While all you need to enter is the field name and an array of select options for the function to work, it offers the flexability to build very complex select tags if needed.  The selected parameter allows for a default option to be selected.  The "option" parameter allows for extra arguments to be inserted inside of the input tag while the "prepend" and "append" parameters allow for additional output to be added before and after the tag.   The indent tag allows for indenting the output HTML for easier reading.
     
Function:
  function build_select_field($name, $select_array, $selected = '', $option = '', $prepend = '', $append = '', $indent = '') {
// Function written by Marcus L. Griswold (vujsa)
// Can be found at http://www.handyphp.com
// Do not remove this header!
    $field = $indent . $prepend . "<select name=\"$name\"";
    if($option){
        $field .= " $option";
    }
    $field .= ">\n";
    for ($x = 0; $x < count($select_array); $x++) {
        if ($select_array[$x] == $selected) {
            $field .= $indent . "\t<option selected>$select_array[$x]</option>\n";
        }
        else {
            $field .= $indent . "\t<option>$select_array[$x]</option>\n";
        }
    }
    $field .= $indent . "</select>" . $append . "\n";
    return $field;
}
   
 
Usage:
  echo build_select_field('sample', array('Option 1', 'Option 2', 'Option 3'), 'Option 2', 'multiple', '<b>Options: </b>', '<br />', "\t\t\t");
     
Result:
 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>Options: </b><select name="sample">
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<option>Option 1</option>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<option selected>Option 2</option>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<option>Option 3</option>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</select><br />
     
Notes:
  This is only really practical if you are planning to add a lot of select fields manually.  Using a loop to build a form would be a good substitute for this kind of manual form creation.


{mos_sb_discuss:3}
Last Updated on Thursday, 11 January 2007 01:39