Ari
Ari

Reputation: 4969

php - Strange Behaviour In date() inside For Loop

I am trying to show month shorten name using date() inside for loop. But it doesn't want to return all of the month names, instead of just the first month name that is Jan.

    for($d=1; $d<=12; $d++){

    if($d < 10) {
    $s = 0 . $d;
    echo date("M", $s) . '<br/>';
    }

    }

It will return:

Jan
Jan
Jan
Jan
Jan
Jan
Jan
Jan
Jan
Jan

I don't know why the value of variable $d won't increment if it is located inside the date() function.

Can someone here explain me why it is happened like that?

Best Regards

Upvotes: 0

Views: 86

Answers (4)

cornelb
cornelb

Reputation: 6066

for ($m=1; $m<=12; $m++) {
    $month = date('M', strtotime("2014-$m-01"));
    echo $month. '<br>';
}

Upvotes: 0

웃웃웃웃웃
웃웃웃웃웃

Reputation: 11984

If you want to print the next 12 months from current date this will help you.

<?php
for ($m=1; $m<=12; $m++) {
    $month = date('F', mktime(0,0,0,$m, 1, date('Y')));
    echo $month. '<br>';
}
?>

What you are doing is simply looping current day 12 times and printing the same dates month in each iteration. Thats why you are getting the same month.

Upvotes: 1

user3205578
user3205578

Reputation:

for($d=1; $d<=12; $d++){
$myDate = mktime(1,1,1,$d,1,2014);
echo date("M", $myDate) . '<br/>';

}

This has been tested. Output:

Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec

...

Basically, the second parameter of the date() function needs to be a timestamp (in seconds).

The mktime() function will create a timestamp based on the hours/minutes/seconds/months/days/years that you provide.

https://www.php.net/mktime

Upvotes: 1

S Korolev
S Korolev

Reputation: 346

Date() requires timestamp as second parameter, not "month number" as you provide. So, for seconds 1-12 from Unix epoch, month will be January.

Upvotes: 1

Related Questions