tags:

views:

86

answers:

2

Below is an old PHP function I have for a dropdown list for users to select there birthdate, this is just the day date portion of it, you can see that it uses str_pad to add on a 0 to the numbers 1-9, is there a better way of doing this?

<?PHP
$date_combo .= '<select name="' . $pre . 'day" class="' .$style. '">';
$date_combo .= "<option value=''>Day</option>";
for ($i = 1; $i <= 31; $i++) {
    $date_combo .= " <option ";
    if ($i == $selected_date_day) {
     $date_combo .= " selected ";
    }
    $date_combo .= " value='" . str_pad($i, 2, "0", STR_PAD_LEFT) . "'>" . str_pad($i, 2, "0", STR_PAD_LEFT) . "</option>";
}
$date_combo .= "</select> ";

echo $date_combo;
?>
A: 

You could make a generic function that accepts an array in order to build a select.

 function formSelect($name, array $options, $selected)
 {
      $output = '<select name="' . $name . '">';

      foreach($options as $key => $value)
      {
           $output .= '<option value="' . $key . '"';

           if($selected == $key) {
                $output .= ' selected="selected"';
           }

           $output .= '>' . $value . '</option>';
      }

      $output .= '</select>';

      return $output;
 }

You should probably escape your output and a few other things, sorry threw that together.

Then you can build your array of options and pass that in. Looks much nicer to build your options list and then just call:

 echo formSelect('birth[day]', $days, 1);
smack0007
+1  A: 

An alternative to str_pad is to use sprintf.
The code:

str_pad($i, 2, "0", STR_PAD_LEFT)

becomes:

sprintf("%02d", $i)

It will print $i as an integer that is 2 characters wide and padded with zeros.
See the sprintf documentation.

Peter Olsson
that works great thanks
jasondavis