Home » Php » PHP display 01 instead of 1

PHP display 01 instead of 1

Posted by: admin July 12, 2020 Leave a comment

Questions:

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?

How to&Answers:

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>';

Answer:

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

Answer:

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>';
}