w3resource

PHP Date Exercises : Last 6 months from the current month

PHP date: Exercise-22 with Solution

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

PHP Code Editor:

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

Previous: Write a PHP script to convert seconds into days, hours, minutes and seconds.
Next: Write a PHP script to get the current month and previous three months.

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.