Menu

Get Last 7 Dates in Array Using PHP

PHP By Dec 10, 2016 1 Comment

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.



function get7DaysDates($days, $format = 'd/m'){
    $m = date("m"); $de= date("d"); $y= date("Y");
    $dateArray = array();
    for($i=0; $i<=$days-1; $i++){
        $dateArray[] = '"' . date($format, mktime(0,0,0,$m,($de-$i),$y)) . '"'; 
    }
    return array_reverse($dateArray);
}

Implementation Code

get7DaysDates(7, 'd-m-Y');

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.

Author

Hello i am Vivek Moyal PHP developer and writes tutorials for students and beginners. Love to explore new cities

1 Comment

  1. John Smith says:


    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 comment

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