Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP display 01 instead of 1 [duplicate]

Tags:

php

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?

like image 970
Satch3000 Avatar asked Feb 01 '13 11:02

Satch3000


People also ask

How can I print 01 instead of 1 in PHP?

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?

How can I get the last two digits of a number in PHP? $number = 12356; $lastDigit = $number % 10; echo $lastDigit; // 6.

How do I cast a string in PHP?

Answer: Use the strval() Function You can simply use type casting or the strval() function to convert an integer to a string in PHP.


2 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>';
like image 89
Prasanth Bendra Avatar answered Oct 05 '22 23:10

Prasanth Bendra


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>';
}
like image 45
Lix Avatar answered Oct 06 '22 01:10

Lix