Reputation: 724
Am am current facing a problem that need a solution ASAP.
I am trying to list all months of the year by using the following code:
for ($m = 1; $m <= 12; $m++) {
$month = date('F', mktime(0, 0, 0, $m));
echo $month . '<br/>';
}
But am getting the following unexpected output:
January
March
March
May
May
July
July
August
October
October
December
December
What am I doing wrong please help!!!
Upvotes: 7
Views: 50723
Reputation: 3193
I know this is old, but here is a different PHP 7+ DateTime
based approach to get an array of month names:
$monthSet = array_map(
fn (int $m): string => (DateTime::createFromFormat('m-d', "$m-1")->format('F')),
range(1, 12),
);
Explanation:
range()
produces an array [1...12
]array_map()
runs the arrow function on each of these numeric months $m
createFromFormat()
is passed $m
and 1
as the day (otherwise the day defaults to the current day and e.g. Feb-31 would overflow to the next month).Slightly more verbose, but uses the DatePeriod
and DateInterval
for their intended purpose (rather than just hardcoding 1-12).
$monthSet = array_map(
fn(\DateTimeImmutable $dt): string => $dt->format('M'),
iterator_to_array(new \DatePeriod(
new \DateTimeImmutable('first day of jan'),
new \DateInterval('P1M'),
11,
)),
);
Explanation:
DatePeriod
returns an iteratorDateInterval('P1M')
sets an interval of 1 monthUpvotes: 2
Reputation: 35572
not as with mktime but equally powerful
$array = array("January", "February",.....);
for ($m=0; $m<12; $m++) {
echo $array[$m]. '<br>';
}
Upvotes: 10
Reputation: 9
If you use laravel
@for ($x = 1; $x <= 12; $x++)
<option value="{{$x}}">{{date('F', mktime(0, 0, 0, $x, 10))}}</option>
@endfor
Upvotes: -1
Reputation: 99
Pay attention to the localization.
You can also use this
setlocale(LC_TIME, 'it_IT');
for($m=1;$m<=12;$m++){
echo strftime("%B", mktime(0, 0, 0, $m, 12));
}
Changing the parameter on the function setlocale() you can display the localized text.
Upvotes: 4
Reputation: 1114
I guess you should loop it in this manner.
for($i = 1 ; $i <= 12; $i++)
{
echo date("F",strtotime(date("Y")."-".$i."-01"));
echo "<br/>";
}
Or in your case, you want to use mktime()
for($i = 1 ; $i <= 12; $i++)
{
echo date("F",mktime(0,0,0,$i,1,date("Y")));
echo "<br/>";
}
Upvotes: 8
Reputation: 7104
Try this:
for ($m=1; $m<=12; $m++) {
$month = date('F', mktime(0,0,0,$m, 1, date('Y')));
echo $month. '<br>';
}
Upvotes: 40
Reputation: 32912
Set day
in mktime()
to 1
, otherwise conversion is performed: 30.2.2012 = 1.3.2012
$month = date('F', mktime(0,0,0,$m,1));
Upvotes: 5