views:

457

answers:

4

Needs to be padded to this: str_pad($Month, 2, "0", STR_PAD_LEFT) but how/where???

/*******creates the month selection dropdown array****/

 function createMonths($id='month_select', $selected=null)
    {
        /*** array of months ***/
        $months = array(
                1=>'Jan',
                2=>'Feb',
                3=>'Mar',
                4=>'Apr',
                5=>'May',
                6=>'Jun',
                7=>'Jul',
                8=>'Aug',
                9=>'Sep',
                10=>'Oct',
                11=>'Nov',
                12=>'Dec');

        /*** current month ***/
        $selected = is_null($selected) ? date('m') : $selected;

        $select = '<select name="'.$id.'" id="'.$id.'">'."\n";
        foreach($months as $key=>$mon)
        {
            $select .= "<option value=\"$key\"";
            $select .= ($key==$selected) ? ' selected="selected"' : '';
            $select .= ">$mon</option>\n";


        }
        $select .= '</select>';
        return $select;
    }

/********displays the month selection with current month selected/*******</br>
 echo createMonths('Month', date ('m')); 

/******DISPLAYS MONTH AS (4) INSTEAD OF REQUIRED (O4) --- @:( /*****</br>
echo $_POST['Month'];
A: 

Well, assuming it's the value you want to be padded, it's here:

$select .= "<option value=\"$key\"";

becomes

$select .= '<option value="'.str_pad($key, 2, "0", STR_PAD_LEFT).'"';

This assumes that you don't want it padded when you're doing the check against $selected, if you do, you need to do it at the beginning of the loop, overwriting the value in $key, and then you can use your original code, like so:

foreach($months as $key=>$mon)
{
    $key = str_pad($key, 2, "0", STR_PAD_LEFT);
    $select .= "<option value=\"$key\"";
    $select .= ($key==$selected) ? ' selected="selected"' : '';
    $select .= ">$mon</option>\n";
}
Chad Birch
Chad ...I love you ;DI tried it on that select before but I kept losing track of the quotes and ended up filling my swearbox...thanks so much.
Brainache
A: 

Could you create your array using: '01'=>'Jan', ...

rvarcher
+1  A: 

You can use printf() or sprintf() with a format string:

$m = sprintf('%02d', (int) $_POST['Month']);
Tom Haigh
A: 

when you say:

$select .= ">$mon</option>\n";

you should use the str_pad function, like this:

$select .= ">" . str_pad($mon, 2, "0", STR_PAD_LEFT) . "</option>\n";
Scott M.
That would attempt to pad the month names with zeros, but would never do anything because none of them are shorter than 2 characters.
Chad Birch