Display months with two-digits and with month names in PHP
html, php
Solution
To output the months on two-digits
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);
To output the month as a name
For the literal month part, you can use the `DateTime` class (see PHP doc).
$date = DateTime::createFromFormat('!m', $x);
$monthName = $date->format('F');
The two running together
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>';
}
Problem
I have a loop to display months in a form. I want to display months in two different formats: - With two digits like this: 01, 02, 03... - With plain text like this: January, February... 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>'; ```