tags:

views:

491

answers:

3

I am trying to create an array starting with today and going back the last 30 days with PHP and I am having trouble. I can estimate but I don’t know a good way of doing it and taking into account the number of days in the previous month etc. Does anyone have a good solution? I can’t get close but I need to make sure it is 100% accurate.

+7  A: 

Try this:

<?php    
$d = array();
for($i = 0; $i < 30; $i++) 
    $d[] = date("d", strtotime('-'. $i .' days'));
?>
Terw
I think you meant for the date to be assigned to $d[i], not $d[].
Matt
Matt: No $d[] is better.
OIS
A: 

You can use time to control the days:

for ($i = 0; $i < 30; i++)
{
    $timestamp = time();
    $tm = 86400 * $i; // 60 * 60 * 24 = 86400 = 1 day in seconds
    $tm = $timestamp - $tm;

    $the_date = date("m/d/Y", $tm);
}

Now, within the for loop you can use the $the_date variable for whatever purposes you might want to. :-)

Pedrin
Pedrin, watch out for this method using time. I used to do this, then noticed that it won't calculate correctly at certain times involving day-light savings time.Instead, I would advise using the strtotime function.-Matt
Matt
A: 

thanks a lot.... :)

Mehedi Hasan