w3resource

PHP Date Exercises : Last 6 months from the current month


22. Last 6 Months from Current Month

Write a PHP script to get the last 6 months from the current month.

Sample Solution:

PHP Code:

<?php
// Initialize an empty array to store the months
$months = [];

// Loop through 6 iterations to generate the last 6 months
for ($i = 1; $i <= 6; $i++) 
{
    // Generate the date string for the first day of the month $i months ago
    $date = date('Y-m-01', strtotime(date('Y-m-01') . " -$i months"));
    
    // Append the date string to the $months array
    $months[] = $date;
}

// Output the array containing the last 6 months
var_dump($months);
?>

Output:

array(6) {                                                  
  [0]=>                                                     
  string(8) "2017-01%"                                      
  [1]=>                                                     
  string(8) "2016-12%"                                      
  [2]=>                                                     
  string(8) "2016-11%"                                      
  [3]=>                                                     
  string(8) "2016-10%"                                      
  [4]=>                                                     
  string(8) "2016-09%"                                      
  [5]=>                                                     
  string(8) "2016-08%"                                      
} 

Explanation:

In the exercise above,

  • for ($i = 1; $i <= 6; $i++): Initiates a for loop to iterate through the last 6 months.
  • $months[] = ...: Appends each generated date string to the '$months' array.
  • date('Y-m-01', strtotime(date('Y-m-01') . " -$i months")): Generates the date string for the first day of the month $i months ago.
  • var_dump($months);: Outputs the array containing the last 6 months for debugging purposes.

Flowchart :

Flowchart: Last 6 months from the current month

For more Practice: Solve these Related Problems:

  • Write a PHP script to generate an array of the last 6 months’ names starting from the current month using DateTime and modify.
  • Write a PHP function that returns the previous 6 months in chronological order from the current date.
  • Write a PHP program to display the last 6 months along with their numerical representations (e.g., 03 for March).
  • Write a PHP script to calculate and output the last 6 months in a single line, separated by commas.

Go to:


PREV : Convert Seconds into Days, Hours, Minutes, Seconds.
NEXT : Current Month and Previous Three Months.

PHP Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.