Get Last 7 Dates in Array Using PHP

By | December 10, 2016

While working over some project where i have to show the data in Chart according to the last 7 days. I was stuck over to get the last 7 dates for further working. So here i am writing the function through which i got the last 7 Dates in Array using PHP.

In this i have created a function and after that a single line to call it anywhere in the project.



Implementation Code

You can use the above line to get the array of the dates. You can change the date format by changing the date separator.

Hope you found our helpful and useful.

One thought on “Get Last 7 Dates in Array Using PHP

  1. John Smith


    function get_last_x_days( $days = 7, $format = 'Y-m-d' ) {
    $month = date( 'm' );
    $day = date( 'd' );
    $year = date( 'Y' );
    $date_array = array();
    for ( $i = 0; $i <= $days - 1; $i++ ) {
    $date_array[] = date( $format, mktime( 0, 0, 0, $month, ( $day - $i ), $year ) );
    }

    return $date_array;
    }

    // using examples
    get_last_x_days( 7, 'Y/m/d' );
    array_reverse( get_last_x_days() ); // defaults: days = 7, format = 'Y-m-d'

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.