Create an Array of The Last X Days using PHP

Today I needed to generate a graph that showed activity over the last 30 days. Realizing I was going to have to create multiple customizable graphs in the future, I wrote a simple function that takes an argument for number of days and then returns an array of the last X number of days from today going backwards. It could be easily modified to find the next 30 days as well. Since days are passed as an argument, you could easily find an array of the last 7 days or next 7 days. You could also dynamically find the number of days in the month and count back each day until the start of the month.

Here is the function to count back the last x number of days:

<?PHP
 
    /******************************************************************
    //THIS METHOD RETURNS A SET OF DATES IN AN ARRAY BASED ON INPUT
    *******************************************************************/
    function createDatesArray($days) {
 
       //CLEAR OUTPUT FOR USE
       $output = array();
 
        //SET CURRENT DATE
       $month = date("m");
       $day = date("d");
       $year = date("Y");
 
        //LOOP THROUGH DAYS
       for($i=1; $i<=$days; $i++){
            $output[] = date('Y-m-d',mktime(0,0,0,$month,($day-$i),$year));
       }
 
       //RETURN DATE ARRAY
       return $output;
 
   }
 
?>

Here is an example of it in use:

<?PHP
 
    //BUILD ARRAY OF DATES USING FUNCTION
    $dates = createDatesArray("30");
 
    //OUTPUT A LIST OF THE LAST 30 DAYS IN ORDER
    foreach($dates as $date) {
        echo($date . "<br />");
    }
 
?>

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Comments

great function!!!!! thanks a lot…

Leave a comment

(required)

(required)