Get Last 7 Dates in Array Using PHP

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.

1 Comment

  1. 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'

Leave a Reply

Your email address will not be published.


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">