Gosi
Gosi

Reputation: 2003

Getting the latest 6 months in ascending order

Objective: To have the months display in a graph in ascending order [eg; Dec 2018, Jan 2019, Feb 2019]

I tried the solution here:

PHP: get last 6 months in format month year

This works well, just that it displays the months in descending order.

So I tried to rewrite that code to display it in ascending order.

Original Code:

<?php
echo date('F, Y');
for ($i = 1; $i < 6; $i++) {
  echo date(', F Y', strtotime("-$i month"));
}
?>

This is what I tried:

<?php

$sixMonthAgo = date("F Y",strtotime("-5 month")); // To get the month 6 month ago

echo $sixMonthAgo;
for ($i = 1; $i < 6; $i++) {
  echo date(', F Y', strtotime("-$i month"));
}

?>

But I realised that my logic is all wrong here. True enough, I got the 6 month ago month in $sixMonthAgo, but my logic of the loop is wrong.

My loop is getting the current date and then subtracting the months accordingly to i value. How do I replace that date to the value of $sixMonthAgo.

Something like this: echo test(', F Y', strtotime("+$i month"));

Upvotes: 0

Views: 344

Answers (1)

idstam
idstam

Reputation: 2878

Iterate from high to low. I think this would work.

<?php
echo date('F, Y');
for ($i = 5; $i >= 0; $i--) {
  echo date(', F Y', strtotime("-$i month"));
}
?>

Upvotes: 1

Related Questions