S.A.
S.A.

Reputation: 57

all months in string format not displayed correct using foreach in php

Below i used foreach loop just to print all months like January to December

foreach(range(1,12) as $i)
{
 echo $pmoth =date("F", mktime(0,0,0,$i));
}

Refer screenshot: In screenshot instead of february it displays march

enter image description here

Upvotes: 2

Views: 66

Answers (2)

Peter
Peter

Reputation: 9113

You could do the following. It's a bit more code but it looks a great deal better.

$period = new DatePeriod(
    new DateTime('2018-01-01'), 
    new DateInterval('P1M'),
    new DateTime('2019-01-01')
);

foreach ($period as $dt) {
    echo $dt->format('F') . PHP_EOL;
}

Upvotes: 0

B. Desai
B. Desai

Reputation: 16436

Pass date parameter also in last other wise it takes current date(30) so for February it is not valid date. That's why it display march

foreach(range(1,12) as $i)
{
 echo $pmoth =date("F", mktime(0,0,0,$i,1));
}

Upvotes: 7

Related Questions