PHP Form Helper — Quick & Easy SELECT Dropdowns

By  on  

One of the most time-consuming parts of my job is creating web forms. PHP web forms generally aren't difficult but they take a lot of time. Any time I can save when creating web forms is great, so I've created a helper function for creating HTML <select> elements.

The Code

function form_select($name,$options,$selected = '',$params = '')
{
    $return = '<select name="'.$name.'" id="'.$name.'"';
    if(is_array($params))
    {
        foreach($params as $key=>$value)
        {
            $return.= ' '.$key.'="'.$value.'"';
        }
    }
    else
    {
        $return.= $params;
    }
    $return.= '>';
    foreach($options as $key=>$value)
    {
        $return.='<option value="'.$value.'"'.($selected != $value ? '' : ' selected="selected"').'>'.$key.'</option>';
    }
    return $return.'</select>';
}

The Explanation

The function accepts four arguments, two required, two optional. Arguments include:

  • $name - name (doubles as the id) of the select element. Required.
  • $options - a key=>value array of keys (Wisconsin) and values (ex: WI). Required.
  • $selected - the previously selected value (ex: WI). Optional.
  • $params - an key=>value array or string ('onchange="alert('you changed me!');"'). Optional.

The Usage

echo 'State: ', form_select('state', array('Michigan'=>'MI', 'Minnesota'=>'MN', 'Wisconsin'=>'WI', 'Wyoming'=>'WY'),'WY', 'onchange="alert(\'Change\');"');

Would you use the script? Do you know any ways to improve it? Share!

Recent Features

  • By
    Send Text Messages with PHP

    Kids these days, I tell ya.  All they care about is the technology.  The video games.  The bottled water.  Oh, and the texting, always the texting.  Back in my day, all we had was...OK, I had all of these things too.  But I still don't get...

  • By
    5 HTML5 APIs You Didn&#8217;t Know Existed

    When you say or read "HTML5", you half expect exotic dancers and unicorns to walk into the room to the tune of "I'm Sexy and I Know It."  Can you blame us though?  We watched the fundamental APIs stagnate for so long that a basic feature...

Incredible Demos

  • By
    Animated AJAX Record Deletion Using MooTools

    I'm a huge fan of WordPress' method of individual article deletion. You click the delete link, the menu item animates red, and the item disappears. Here's how to achieve that functionality with MooTools JavaScript. The PHP - Content & Header The following snippet goes at the...

  • By
    jQuery Wookmark

    The first thing that hits you when you visit Pinterest is "Whoa, the columns are the same width and the photos are cut to fit just the way they should."  Basic web users probably think nothing of it but as a developer, I can appreciate the...

Discussion

  1. A very handy function. However a lot of frameworks these days offer form helper objects which have something like this already defined… and other handy things too.

  2. Chuck

    I have created a simple form creator script (I need to polish it and release it). It does the following:

    Step 1: Textarea that accepts comma delimited input for input names (First Name, Last Name, Address, etc.)

    Step 2: Presented with a form that lists all of the above inputs with radio options for type of form (Text Box, Radio, Password, Hidden, etc.)

    Step 3: Prints out the fields into a textbox for copy-paste.

    *I plan on making a dropdown so you can choose the ‘template’ you wish to populate the form with. Right Now it writes out:

    .label for=’input name(lowercased and underscored)’>input name(uppercased)-label>
    .input type=’etc’ name =’input name(lowercased and underscored)’ value=” />
    .br class=’clear’ />

    This makes creating a css form with multiple values take less than 5 minutes. Then you can do some quick CSS tweaks and be done with it.

  3. Sounds good Chuck — be sure to let me know when it’s released!

  4. c_wd

    an example of usage would make this more friendly.

    $hours4select = array(1=>1, 2=>2, 3=>3, 4=>4, 5=>5, 6=>6, 7=>7, 8=>8, 9=>9, 10=>10, 11=>11, 12=>12);
    
    echo form_select('class_time_hour', $hours4select);
    
  5. David,
    Thank you very much for the helper function. I will use it in my projects.

    In the earlier posts, I read that @Chuck mentioned about a simple form creator script. In fact, such a tool already exists and I use that for my projects. This tool is called: Form & PHP/MySQL Generator (FPMG) & you can visit it at: http://www.fpmg.co.cc

    So I don’t see a point in reinventing the wheel, unless the functionality that @Chuck wants to implement, differs greatly.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!