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?
Using sprintf() Function: The sprintf() function is used to return a formatted string. Syntax: sprintf(format, $variable) // Returns the variable formatted according to the format provided. Example 1: This example uses sprintf() function to display the number with leading zeros.
How can I get the last two digits of a number in PHP? $number = 12356; $lastDigit = $number % 10; echo $lastDigit; // 6.
Answer: Use the strval() Function You can simply use type casting or the strval() function to convert an integer to a string in PHP.
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>';
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>';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With