I have a loop to display months in a form.
I want to display months in two different formats:
Just like this:
<option value="01">January</option>
<!-- ... -->
<option value="12">December</option>
The problem is, I can't manage to display this.
Here is my code so far:
echo '<select name="month">';
for ($x=1; $x<=12; $x++)
{
$val=strlen($x);
if($val==1)
{
echo '<option value="'.'0'.$x.'">'.'0'.$x.'</option>';
} else {
echo '<option value="'.$x.'">'.$x.'</option>';
}
}
echo '</select>';
You have two main choices:
str_pad()
- see PHP documentation here
sprintf()
- see PHP documentation there
You would use the two like that, assuming $x
is your numerical month (1, 2, 3...):
// with str_pad()
$month = str_pad($x, 2, "0", STR_PAD_LEFT);
// with sprintf()
$month = sprintf('%02d', $x);
For the literal month part, you can use the DateTime
class (see PHP doc).
$date = DateTime::createFromFormat('!m', $x);
$monthName = $date->format('F');
It goes like this in your case, with str_pad()
:
for ($x = 1; $x <= 12; $x++)
{
$month = str_pad($x, 2, "0", STR_PAD_LEFT);
$date = DateTime::createFromFormat('!m', $x);
$monthName = $date->format('F');
echo '<option value="'.$month.'">'.$monthName.'</option>';
}
Using str_pad()
and mktime()
you can do this
for ($x = 1; $x <= 12; $x++) {
$monthNum = str_pad($x, 2, "0", STR_PAD_LEFT);
$monthName = date("F", mktime(0, 0, 0, $monthNum, 10));
echo '<option value='.$monthNum.'">'.$monthName.'</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