Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display months with two-digits and with month names in PHP

Tags:

html

php

I have a loop to display months in a form.

I want to display months in two different formats:

  1. With two digits like this: 01, 02, 03...
  2. 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>';
like image 933
user3097736 Avatar asked Feb 13 '23 21:02

user3097736


2 Answers

To output the months on two-digits

You have two main choices:

  1. str_pad() - see PHP documentation here
  2. 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>';
}
like image 76
Jivan Avatar answered Feb 17 '23 01:02

Jivan


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>';
}
like image 32
dpDesignz Avatar answered Feb 17 '23 02:02

dpDesignz