Search code examples
phparraysdate

Generate a flat array containing dates for the last 31 days


I'm trying to create an array that contains the last 31 dates. e.g.

$dates = array(
    "2011-03-22",
    "2011-03-21",
    "2011-03-20",
    "2011-03-19",
    ...........
    "2011-02-22"
);

How can this be done?


Solution

  • Using the DateTime object, its fairly straight forward. (Available from PHP 5.2 onwards).

    $dates = array();
    $date = new DateTime();
    for($i = 0; $i < 31; $i++) {
        $dates[] = $date->format('Y-m-d');
        $date->modify('-1 day');
    }