10

Possible Duplicate:
Formatting a number with leading zeros in PHP

I am populating a select box with php.

This is the code:

$select_month_control = '<select name="month" id="month">';
for($x = 1; $x <= 12; $x++) {
$select_month_control.= '<option value="'.$x.'"'.($x != $month ? '' : ' selected="selected"').'>'.date('F',mktime(0,0,0,$x,1,$year)).'</option>';
}
$select_month_control.= '</select>';

This is creating this:

<select id="month" name="month">
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>
<option value="7">July</option>
<option value="8">August</option>
<option selected="selected" value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>

The problem is that I need the 1, 2, 3 etc to be 01, 02, 03 etc... Like this:

<option value="01">January</option>

instead of:

<option value="1">January</option>

How can I do this?

Community
  • 1
  • 1
Satch3000
  • 47,356
  • 86
  • 216
  • 346
  • 3
    Do you know about [`sprintf`](http://php.net/manual/en/function.sprintf.php)? Try echo `sprintf('%02d', 1);` – Jon Feb 01 '13 at 12:00
  • 2
    See here : http://stackoverflow.com/questions/1699958/formatting-a-number-with-leading-zeros-in-php – FreudianSlip Feb 01 '13 at 12:00
  • You use tenary to display `selected`, it can be used for the option value as well: `( strlen($x)==1? '0'.$x: $x )` – rlatief Feb 01 '13 at 12:18

3 Answers3

28

You can use sprintf("%02d", $number) to format strings.

Edit: See http://www.php.net/manual/en/function.sprintf.php for more information about format strings

Masse
  • 4,334
  • 3
  • 30
  • 41
16

user str_pad ref : http://php.net/manual/en/function.str-pad.php

$select_month_control = '<select name="month" id="month">';
for($x = 1; $x <= 12; $x++) {
$select_month_control.= '<option value="'.str_pad($x, 2, "0", STR_PAD_LEFT).'"'.($x != $month ? '' : ' selected="selected"').'>'.date('F',mktime(0,0,0,$x,1,$year)).'</option>';
}
$select_month_control.= '</select>';
Prasanth Bendra
  • 31,145
  • 9
  • 53
  • 73
  • Your code has a syntax error. Double check next time you copy a line from somewhere ;) – Lix Feb 01 '13 at 12:10
6

You might want to try using the str_pad() function within your loop :

str_pad — Pad a string to a certain length with another string

for($x = 1; $x <= 12; $x++) {
  $value = str_pad($x,2,"0",STR_PAD_LEFT);
  $select_month_control.= '<option value="'.$value.'">'.$value.'</option>';
}
Lix
  • 47,311
  • 12
  • 103
  • 131